此问题与listview item重用有关,请创建以下类。
public class LocalOnclickListener : Java.Lang.Object, View.IOnClickListener
{
public void OnClick(View v)
{
HandleOnClick();
}
public System.Action HandleOnClick { get; set; }
}
然后在您的 GetView 方法中,像下面的代码一样使用它。它会使点击事件在 TextView 中只执行一次。
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null) // no view to re-use, create new
view = mainActivity.LayoutInflater.Inflate(Resource.Layout.layout1, null);
TextView textView = view.FindViewById<TextView>(Resource.Id.textView1);
textView.Text = items[position];
var local = new LocalOnclickListener();
local.HandleOnClick = () =>
{
Toast.MakeText(mainActivity, "click", ToastLength.Short).Show();
};
textView.SetOnClickListener(local);
return view;
}
或者您可以简单地使用以下代码。
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if (view == null) // no view to re-use, create new
view = mainActivity.LayoutInflater.Inflate(Resource.Layout.layout1, null);
view.FindViewById<TextView>(Resource.Id.My_textView1).Text = items[position];
TextView textView = view.FindViewById<TextView>(Resource.Id.textView1);
textView.Text = items[position];
// textView.Click += TextView_Click;
if (!textView.HasOnClickListeners)
{
textView.Click += (o, e) =>
{
Toast.MakeText(mainActivity, "click", ToastLength.Short).Show();
};
}
return view;
}
这里有一个类似的帖子,你可以参考一下:
https://forums.xamarin.com/discussion/9244/single-click-on-button-invoking-multiple-clicks