我为ArrayAdapter
的{{1}}定义了一个自定义视图(xml),其中添加了ListView
。我想为每行Button
创建OnClickListener
,但不创建自定义适配器。这是可能的,还是Android会强迫我为Button
创建自定义ArrayAdapter
?
以下是我正在做的事情的片段:
ListView
现在,我想在自定义视图中为glAdapter = new ArrayAdapter<Group>(getActivity(), R.layout.fragment_grouprow, R.id.groupRowText, ListOfGroups);
ListView groupListView = (ListView)mainView.findViewById(R.id.listViewGroupMain);
groupListView.setAdapter(glAdapter);
groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Call function
}
});
添加OnClickListener
。
答案 0 :(得分:1)
您必须在按钮上的getView()
方法集OnClickListener
中实现自己的适配器。这里开始举例:
public class CustomAdapter extends ArrayAdapter<Integer> {
private ListView listView;
public CustomAdapter(Context context, int textViewResourceId, Integer[] objects, ListView listView) {
super(context, textViewResourceId, objects);
this.listView = listView;
}
static class ViewHolder {
TextView text;
Button btn;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Integer color = getItem(position);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
rowView = inflater.inflate(R.layout.list_view_row, parent, false);
ViewHolder h = new ViewHolder();
h.text = (TextView) rowView.findViewById(R.id.item_text);
h.btn = rowView.findViewById(R.id.btn);
rowView.setTag(h);
}
ViewHolder h = (ViewHolder) rowView.getTag();
h.text.setText(color);
h.indicator.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// DO what you want to recieve on btn click there.
}
});
return rowView;
}
}
ViewHolder在这里进行优化。你可以阅读这个there。