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

标签 java android hashmap

在此处显示的代码中,我正在膨胀 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/

相关文章:

java - 重新打包依赖并修复pom

java - 移动平均/总算法

Java方法调用

android - 尝试连接华为 IAP SDK 进行 Inapp 支付 - 6003 错误

java - Android自定义 View 布局问题

java - 如何使用 Guava 的 MultiMap 输出唯一键? ( java )

java - 发现不兼容的类型

java - 是否有 API 可以检查系统是否是 android,而不是桌面 jvm?

java - 如何从 Hashmap Java 计算总数

java - hashmap 不保存值?