Stack Overflow Asked by rana hd on November 24, 2021
I’ve created a listview that contains 5 textviews in each row. now I want to click on the last textview and get redirected to a new page. my problem is that I can’t figure out how to access the textview. I tried doing this in my custom adapter:
var t = view.FindViewById<TextView>(Resource.Id.textView5);
t.Click +=delegate {
Android.Widget.Toast.MakeText(context, t.Text, Android.Widget.ToastLength.Short).Show();
};
I used the toast just to see if the function will work. but It didn’t. when I ran the app and clicked on the textview, I kept getting a toast and it didn’t stop. what is the right way to do this?
thanks a lot in advance.
This issue is related to the listview item reuse, please create a following class.
public class LocalOnclickListener : Java.Lang.Object, View.IOnClickListener
{
public void OnClick(View v)
{
HandleOnClick();
}
public System.Action HandleOnClick { get; set; }
}
Then in your GetView Method, use it like following code. It will make the click event execute only once in 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;
}
Or you can simple use following code.
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;
}
Here is a similar thread, you can refer to it:
https://forums.xamarin.com/discussion/9244/single-click-on-button-invoking-multiple-clicks
Answered by Leon Lu - MSFT on November 24, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP