问题
I was curious how best to handle button clicks, inside of a ListFragment
with a custom adapter.
I have an onClickListener
setup for the buttons, but I need to be able to get the item that it was clicked from, since it is within an item, here is the getView
inside the custom adapter.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = _inflater.inflate(R.layout.test_single_item, parent, false);
} else {
view = convertView;
}
TestItemModel item = getItem(position);
((TextView) view.findViewById(R.id.item_label)).setText(item.getName());
((TextView) view.findViewById(R.id.item_id)).setText(item.getId());
ImageView image = (ImageView) view.findViewById(R.id.image_id);
Resources resources = this.getContext().getResources();
image.setImageDrawable(resources.getDrawable(R.drawable.ic_launcher));
Button btn = (Button) view.findViewById(R.id.button_id);
Button btn2 = (Button) view.findViewById(R.id.button_id_2);
Button btn3 = (Button) view.findViewById(R.id.button_id_3);
ol = new OnItemClickListener(position);
btn.setOnClickListener(ol);
btn.setTag(1);
btn2.setOnClickListener(ol);
btn2.setTag(2);
btn3.setOnClickListener(ol);
btn3.setTag(3);
return view;
}
as you can see I used tags to determine which button was clicked and the OnItemClickListener
knows where the position is from the position at which is being called.
I am not sure about the best approach and how to go about doing this properly.
回答1:
Use a switch case as below
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
switch(v.getId())
{
case R.id.button_id :
// btn clicked
Toast.makeText(context," Button1 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
break;
case R.id.button_id2 :
// btn2 clicked
Toast.makeText(context," Button2 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
break;
case R.id.button_id3 :
Toast.makeText(context," Button3 clicked at positon"+v.getTag(), Toast.LENGTH_SHORT).show();
// btn 3 clciked
break;
}
}
};
Use
btn.setOnClickListener(mClickListener);
btn.setTag(position);
btn2.setOnClickListener(mClickListener);
btn2.setTag(position);
btn3.setOnClickListener(mClickListener);
btn3.setTag(position);
Snap of example with two buttons
snap of button 1 clicked at position 0 ie first row

snap of button 2 clicked at position 1 ie second row

来源:https://stackoverflow.com/questions/19487253/how-to-handle-button-clicks-listfragment