在Android中捕获自定义列表视图上的单击
我在ListActivity中使用了一个自定义XML文件来绑定我的db游标。XML文件中的每个项都有2个按钮。我想捕获按钮的点击事件和列表中的位置 这是我的XML文件在Android中捕获自定义列表视图上的单击,android,listadapter,Android,Listadapter,我在ListActivity中使用了一个自定义XML文件来绑定我的db游标。XML文件中的每个项都有2个按钮。我想捕获按钮的点击事件和列表中的位置 这是我的XML文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layo
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/smListName" android:paddingTop="2dip" android:paddingBottom="3dip" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:textSize="22dip" />
<Button android:id="@+id/smListCompleted" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:textStyle="bold" android:textColor="#0000ff" />
<Button android:id="@+id/smListNotCompleted" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_gravity="right" android:textColor="#ff0000"
android:textStyle="bold" />
</LinearLayout>
我没有使用自定义适配器。现在我想捕获smListNotCompleted和smListCompleted的点击以及行位置
谢谢您必须使用新的适配器。在实施之前,请尝试理解其背后的概念:
class YourNewAdapter extends SimpleCursorAdapter
{
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
btn = (Button)v.findViewById(R.id.yourbutton);
btn.setOnClickListener(YourActivity.this);
btn.setId(position);
btn.setText("sometext");
v.setLongClickable(true);
}
return v;
}
}
在你的活动中
public void onClick(View v)
{
if(v.getId() == R.id.yourbutton id)
{
// do what you want you can also put this on click listener in the getview fn
}
}
由于您需要自定义列表中两个按钮的单击事件(共2个按钮);您需要创建一个自定义列表适配器,在该适配器中,您可以分别为两个按钮添加单击事件,还可以单击位置。我在列表适配器中使用了一个单击事件,并将位置id放入按钮标记中
Button editButton = view.FindViewById(Resource.Id.editPaymentButton_2) as Button;
editButton.Tag = position;
editButton.Clickable = true;
editButton.Click += editButton_Click;
这是我绑定到GetView中的事件的事件
void editButton_Click(object sender, EventArgs e)
{
if (editButtonClicked)
{
return;
}
editButtonClicked = true;
var button = sender as Button;
if (button == null)
return;
//OnEdit((Entities.PaymentTemplate)GetItem((int)button.Tag));
}
谢谢Reno,刚才这么做了,仍然没有收到Toast消息。您可以在自定义适配器本身中为两个按钮添加单击事件。@Tushar是的,这是我在评论中写的,请参阅onclick fn,但在您的情况下,您建议查看ClickListener而不是列表查看项click Listener?。。
void editButton_Click(object sender, EventArgs e)
{
if (editButtonClicked)
{
return;
}
editButtonClicked = true;
var button = sender as Button;
if (button == null)
return;
//OnEdit((Entities.PaymentTemplate)GetItem((int)button.Tag));
}