【问题标题】:How to retrieve value from a map based on object如何根据对象从地图中检索值
【发布时间】:2016-12-26 15:21:10
【问题描述】:

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

我的问题是,如何将每个视图作为键添加到地图中,以及如何在给定键的情况下从地图中检索特定值。我参考了一些帖子,但我不知道如何根据给定的键从地图中获取值,尤其是 我的关键是一个对象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);
}

【问题讨论】:

    标签: java android hashmap


    【解决方案1】:

    首先,我不建议使用对 View 的引用作为 Map 的键 - 这可能会导致引用泄漏和内存问题。而是通过setTag(Object obj) 方法为视图分配一个标签。稍后在单击侦听器中检索调用 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
            }
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      相关资源
      最近更新 更多