如何基于对象从地图中检索值

时间:2016-12-26 15:21:11

标签: java android hashmap

在发布的代码中,我正在给视图充气并将其添加到linearlayout。单击时的每个视图都应打开与其相关的特定文档。所以我想要实现这一点是将每个膨胀的视图添加到地图作为关键和 地图的价值将是文件。

我的问题是,如何将每个视图作为键添加到地图中,以及如何从给定键的地图中重新提取特定值。我提到了一些帖子,但我不知道如何根据给定的密钥从地图中获取值 我的密钥是一个对象查看

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);
}

1 个答案:

答案 0 :(得分:0)

首先,我不建议使用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
        }
});