我有一个带有图像、一对 TextViews 和一个复选框的 ListViews 的自定义 row_item。据我了解,由于 checkBox 是一个可聚焦元素,它会从 listView 中窃取焦点,因此 OnListItemClicked 永远不会被触发,除非我将每个 row_item 设置为不可点击并且我阻止后代的可聚焦性。
然后,为了管理复选框更改,我在适配器 getView 方法中为我的复选框设置了“OnCheckedChangeListener”。
这是一种不好的做法吗?(因为每次调用 getView 时我都在创建新的侦听器)还有其他方法可以做到这一点吗?
我附上了一些代码,以便更容易理解我的意思。
getView 方法:(在 arrayAdapter 内)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/** recycling views */
View row = convertView;
PregoHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PregoHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.thumbnail);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
holder.txtNews = (TextView)row.findViewById(R.id.txtNews);
holder.chBox = (CheckBox) row.findViewById(R.id.checkBox);
row.setTag(holder);
}
else
{
holder = (PregoHolder)row.getTag();
}
Prego Prego = data[position];
holder.txtTitle.setText(Prego.title);
holder.imgIcon.setImageResource(Prego.icon);
holder.txtNews.setText(Prego.news);
holder.chBox.setChecked(Prego.checked);
/** wiring up Listeners...
* (works fine but we are creating new listener each time)
* (Done like this because of the custom list view focusable issue)
*/
holder.chBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton arg0, boolean checked) {
/** Getting the view position in the ListView */
ListView parent = (ListView)(arg0.getParent()).getParent();
int pos = parent.getPositionForView(arg0);
if (checked){
checkedPregons[pos] = true;
pregonsChecked++;
}
else if (!checked){
checkedPregons[pos] = false;
pregonsChecked--;
}
Toast.makeText(context, pregonsChecked+" is/are checked", Toast.LENGTH_SHORT).show();
}
});
row.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//mMode = ((Activity)context).startActionMode(new PregonsActionModes());
ListView parent = (ListView)v.getParent();
int pos = parent.getPositionForView(v);
Toast.makeText(context, "getView should show prego "+pos,Toast.LENGTH_SHORT).show();
}
});
return row;
}
提前致谢。