You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android:ListView按钮点击获位置及Fragment按钮实现

Solutions for Your Xamarin Android Questions

Got it, let's break down solutions for both of your requirements clearly:


1. Get ListView Item Position When Clicking a Button Inside the Item

Since you're using a BaseAdapter<Quotes> for your ListView, you'll handle the button click directly in the adapter's GetView method. Here's how to implement it properly:

First, complete your adapter's GetView method (I'll fill in the missing parts for you):

public class HomeScreenAdapter : BaseAdapter<Quotes> 
{ 
    List<Quotes> items; 
    Activity context; 

    public HomeScreenAdapter(Activity context, List<Quotes> items) : base() 
    { 
        this.context = context; 
        this.items = items; 
    } 

    public override long GetItemId(int position) 
    { 
        return position; 
    } 

    public override Quotes this[int position] 
    { 
        get { return items[position]; } 
    }

    public override int Count 
    { 
        get { return items.Count; } 
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        // Reuse view if possible (ViewHolder pattern is better for performance, but this works for basics)
        View view = convertView ?? context.LayoutInflater.Inflate(Resource.Layout.YourListItemLayout, parent, false);
        
        // Get the current quote item
        Quotes currentQuote = items[position];

        // Locate your button in the list item layout
        Button itemButton = view.FindViewById<Button>(Resource.Id.your_button_id);

        // Option 1: Use Tag to store position (most reliable to avoid closure issues)
        itemButton.Tag = position;
        itemButton.Click += (sender, e) =>
        {
            int clickedPosition = (int)((Button)sender).Tag;
            Quotes clickedItem = items[clickedPosition];
            
            // Do whatever you need with the position/item
            Toast.MakeText(context, $"Clicked item at position: {clickedPosition}", ToastLength.Short).Show();
        };

        // Option 2: Directly capture the position variable (works here since GetView is called per item)
        // itemButton.Click += (sender, e) =>
        // {
        //     Toast.MakeText(context, $"Clicked item at position: {position}", ToastLength.Short).Show();
        // };

        // Bind other data to your list item views (example)
        TextView quoteText = view.FindViewById<TextView>(Resource.Id.quote_text);
        quoteText.Text = currentQuote.QuoteText;

        return view;
    }
}

Key Notes:

  • Using the Tag property is safer for avoiding unexpected behavior with closures, especially if you're reusing views via convertView.
  • For better performance, consider implementing the ViewHolder pattern to avoid repeated FindViewById calls.

2. Implement Button Click in Fragment's OnCreateView Method

In your Fragment, you'll inflate the layout first, then locate the button and attach a click handler. Here's the code:

public class HomeFragment : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        // Inflate your fragment's layout
        View fragmentView = inflater.Inflate(Resource.Layout.HomeFragmentLayout, container, false);

        // Find the button in the fragment layout
        Button fragmentButton = fragmentView.FindViewById<Button>(Resource.Id.fragment_button_id);

        // Attach click event handler
        fragmentButton.Click += FragmentButton_Click;

        return fragmentView;
    }

    // Separate click handler method (cleaner than anonymous delegates for complex logic)
    private void FragmentButton_Click(object sender, EventArgs e)
    {
        // Handle the button click here
        // Use Activity property to get the context for Toast/other operations
        Toast.MakeText(Activity, "Fragment button clicked successfully!", ToastLength.Short).Show();
        
        // Example: If you need to communicate with the parent Activity, use an interface or ViewModel
    }

    // Alternatively, use an anonymous delegate for simple logic:
    // fragmentButton.Click += (sender, e) =>
    // {
    //     Toast.MakeText(Activity, "Fragment button clicked!", ToastLength.Short).Show();
    // };
}

Key Notes:

  • Always use Activity (or Context) from the Fragment instead of ApplicationContext to prevent memory leaks.
  • For more complex interactions between Fragment and Activity, consider using interfaces or a shared ViewModel.

内容的提问来源于stack exchange,提问作者Fatihi Youssef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:04:12