gpt4 book ai didi

java - 如何根据对象从 map 中检索值

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:39 24 4
gpt4 key购买 nike

在此处显示的代码中,我正在膨胀 View 并将其添加到线性布局中。单击每个 View 时应打开与其相关的特定文档。我想要实现这一目标的是将每个膨胀 View 作为键添加到 map 中,并且 map 的值将是文档。

我的问题是,如何将每个 View 作为键添加到 map 中,以及如何从给定键的 map 中检索特定值。我引用了一些帖子,但我不知道如何根据给定的键从 map 中获取值,尤其是我的 key 是一个对象 View

代码:

private void inflateView(String bez, String ges) {
LinearLayout linLay = (LinearLayout) findViewById(R.id.versicherungsListeActivity2mod_linLay_meineDocList_container);

View viewDivider = new View(this);
viewDivider.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
viewDivider.setBackgroundColor(Color.parseColor("#000000"));

LayoutInflater inflator = this.getLayoutInflater();
View view = inflator.inflate(R.layout.versicherung_docs_row_model, null);//<<<<<< this is the view i want to add to the map as a key

ImageView imgViewLogo = (ImageView) view.findViewById(R.id.versicherungslisteactivity2_docs_lisvie_row_model_imgVie_logo);
TextView texVieBez = (TextView) view.findViewById(R.id.versicherungslisteactivity2_docs_lisvie_row_model_texVie_docBezeichnung);
TextView texVieExtraItem = (TextView) view.findViewById(R.id.versicherungslisteactivity2_docs_lisvie_row_model_texVie_addMoreDocs);
TextView texVieGes = (TextView) view.findViewById(R.id.versicherungslisteactivity2_docs_lisvie_row_model_texVie_docGesellschaft);
Button btnMore = (Button) view.findViewById(R.id.versicherungslisteactivity2_docs_lisvie_row_model_btn_more);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imgViewLogo.setImageDrawable(this.getResources().getDrawable(R.drawable.insurance_details_doc, this.getTheme()));
} else {
imgViewLogo.setImageDrawable(this.getResources().getDrawable(R.drawable.insurance_details_doc));
}

texVieBez.setText(bez);
texVieGes.setText(bez);
btnMore.setVisibility(View.VISIBLE);

linLay.addView(view);

linLay.addView(viewDivider);
}

最佳答案

首先,我不建议使用对 View 的引用作为 Map 的键 - 这可能会导致引用泄漏和内存问题。而是通过 setTag(Object obj) 方法将标签分配给 View 。稍后在点击监听器中调用 map.get(key) 检索文档,其中 key 是您分配的标签。

inflateView 内部:

String tag = "Something unique for a key" // can be any Object not necessarily a String
view.setTag(tag);
map.put(tag, referenceToDocument);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Object document = map.get(view.getTag());
// do whatever you like with the document
}
});

关于java - 如何根据对象从 map 中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333180/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com