在将自定义RowView
扩展到绑定到ListView
的ListAdapter
后,我遇到了一个问题。我在我的ListView
项目上注册了一个ItemClick
事件,当它被单击时,我希望DetailView
会被打开。然而,我的点击事件似乎被覆盖了,因为当我点击ListView
项目时什么都没有发生。
以下是使用ListView
:的ExplorerActivity
类的示例
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.ExplorerView);
exampleListView = FindViewById<ListView>(Resource.Id.exampleListView);
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"TestDb.db3");
SQLiteConnection myConn = new SQLiteConnection(dbPath);
allItems = dbHelper.GetAllItems();
exampleListView.Adapter = new exampleListAdapter(this, allItems);
exampleListView.ItemClick += exampleListView_ItemClick;
}
示例ListAdapter
代码:
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = items[position];
if (convertView == null)
{
convertView = context.LayoutInflater.Inflate(Resource.Layout.CustomRowView, null);
}
convertView.FindViewById<TextView>(Resource.Id.ItemTextView).Text = item.Name;
}
如果我为自定义RowView
充气,我会丢失我在ListView
项目上注册的点击事件吗?我无法将该事件添加到ListAdapter
中的整个自定义RowView
中,所以我认为它将是一个ListView.ItemClick
事件。
我在ListView
上的点击事件是否被自定义RowView
忽略?RowView
的每个实例仍然是ListView
项,对吗?
我似乎找不到合适的对象,例如RowView
不是一个东西,那么在膨胀我的自定义RowView
后,我如何将事件绑定到ListView
项?
我曾尝试在资源管理器活动中设置断点,但从未命中,这就是为什么我认为该事件不再在ListView_ItemClick
上注册的原因。
如果我扩展自定义RowView,我会丢失在ListView项上注册的点击事件吗?
不,您不会丢失ListView
的项目点击事件。项目点击事件应正确触发。
自定义RowView是否忽略了ListView上的单击事件?RowView的每个实例仍然是ListView项,对吗?
我做了一个基本的测试演示,项目点击事件可以正确触发。你可以在这里试试我的演示
我似乎找不到合适的对象,例如RowView不是一个东西,那么在膨胀我的自定义RowView后,我如何将事件绑定到ListView项?
一种方法是绑定ListView
的Item Click事件。另一种方法是将点击事件绑定到膨胀的视图:
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = mList[position];
if (convertView == null)
{
convertView = mContext.LayoutInflater.Inflate(Resource.Layout.CustomRowView,null);
}
var btn = convertView.FindViewById<Button>(Resource.Id.mBtn);
btn.Click += Btn_Click;
return convertView;
}
private void Btn_Click(object sender, EventArgs e)
{
//do your job here
}
更新:
问题出在按钮上,一旦将按钮添加到行视图中,ItemClick
就无法工作。如果你想让ItemClick
工作,你需要把android:focusable="false"
和android:focusableInTouchMode="false"
添加到每个按钮上,如下所示:
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Click Me"/>