如何显示带有已选中项目的内置行视图?

How do I display a built-in row view with an item already checked?

我正在使用 Xamarin 内置行视图 SimpleListItemSingleChoice

我想显示带有已选中项目的视图,但它不起作用。

我的 ListAdapter 获取作为输入的对象列表,这些对象具有 IsChosen 属性,因此它知道应该选择哪个对象:

public MySproutListAdapter (Activity context, IList<Sprout> mySprouts) : base ()
    {
        this.context = context;
        this.sprouts = mySprouts;
    }

GetView()方法如下:

public override Android.Views.View GetView (int position, 
                                            Android.Views.View convertView, 
                                            Android.Views.ViewGroup parent)
    {
        //Try to reuse convertView if it's not  null, otherwise inflate it from our item layout
        var view = (convertView ?? 
            context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleListItemSingleChoice, parent, false)) as LinearLayout;

        var textLabel = view.FindViewById<TextView>(Android.Resource.Id.Text1);

        textLabel.TextFormatted = Html.FromHtml(sprouts[position].sproutText);

//I thought this line would display the view with the correct item's radio 
//button selected, but it doesn't seem to.
            textLabel.Selected = sprouts[position].IsChosen;

            return view;
        }

我查看了选定列表视图的自定义定义,但由于它是内置视图,我认为自定义定义一定会使事情过于复杂。
如何让内置视图正确显示选中项?

看起来无法从适配器内部检查项目。您需要调用 ListView.SetItemChecked(selectedItemIndex, true)。 Link.

编辑。

对不起,我错了。您在内部 TextView 上设置 Checked == true 但不是在项目本身上。这是工作示例:

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace TestSimpleListItemSingleChoice
{
    [Activity (Label = "TestSimpleListItemSingleChoice", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            var adapter = new TestAdapter (this);
            adapter.Add ("test1");
            adapter.Add ("test2");
            adapter.Add ("test3");
            adapter.Add ("test4");
            FindViewById<ListView> (Resource.Id.listView1).Adapter = adapter;
        }
    }

    public class TestAdapter : ArrayAdapter<string>{
        public TestAdapter(Context context) : base(context, Android.Resource.Layout.SimpleListItemSingleChoice, Android.Resource.Id.Text1){
        }
        public override View GetView (int position, View convertView, ViewGroup parent)
        {
            var view = base.GetView (position, convertView, parent);
            ((CheckedTextView)view).Checked = position == 1;
            return view;
        }
    }
}