如何处理按钮点击声ListFragment [英] How to Handle Button Clicks ListFragment
问题描述
我很好奇如何最好地处理按钮点击,一个 ListFragment
里面有一个自定义适配器。
I was curious how best to handle button clicks, inside of a ListFragment
with a custom adapter.
我对按钮的 onClickListener
设置,但我需要能够得到它从点击的项目,因为它是一个项目中,这里是在 getView
自定义适配器内部。
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;
}
你可以看到我使用的标签,以确定哪个按钮被点击和 OnItemClickListener
知道在哪里的位置从它被调用的位置。
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.
推荐答案
使用的开关情况如下
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;
}
}
};
使用
btn.setOnClickListener(mClickListener);
btn.setTag(position);
btn2.setOnClickListener(mClickListener);
btn2.setTag(position);
btn3.setOnClickListener(mClickListener);
btn3.setTag(position);
例如捕捉有两个按钮
Snap of example with two buttons
按钮1单元点击位置0,即第一行
snap of button 1 clicked at position 0 ie first row
按钮2单元点击在位置1,即第二行
snap of button 2 clicked at position 1 ie second row
这篇关于如何处理按钮点击声ListFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!