setTag和findViewByTag的使用具体解释

在使用ListView或者GridView的时候。 假设想要在Aciviry中获取到Item中的子View,比較频繁的使用是:getChildAt(int position);


之前自己差点儿不会去使用findViewByTag,由于用不须要使用。这次项目须要,使用到了ExpandableListView,上下级的IItem。并且自定义了事件监听,可是事件监听方法的參数列表中没有专递ViewGroup parent和View convertView之类的參数,获取item中的view是行不通的。


这时就想到了setTag和findViewByTag,实现比較简单。例如以下代码:


一:在Adapter中的getView或者getRealChildView下,先找到mSwitch.icon = (ImageView) convertView.findViewById(R.id.swicon);

然后:mSwitch.icon.setTag("obj" + groupPosition + childPosition);    //setTag(Object object),这个object为随意对象,可是一定要保证其唯一性;


二:在Activity中,mIcon = (ImageView) listview.findViewWithTag("obj" + groupPosition + childPosition).findViewById(R.id.swicon);


于是就OK了。


关键代码:adapter中

mSwitch.icon = (ImageView) convertView.findViewById(R.id.swicon);
mSwitch.icon.setTag("obj" + groupPosition + childPosition);


activity中
mIcon = (ImageView) listview.findViewWithTag("obj" + groupPosition + childPosition).findViewById(R.id.swicon);


原文地址:https://www.cnblogs.com/mfmdaoyou/p/6767941.html