我正在使用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;
}
我查看了所选列表视图的自定义定义,但由于它是内置视图,我认为自定义定义必须使事情过于复杂。
如何使内置视图正确显示所选项目?
答案 0 :(得分:1)
看起来无法从适配器内部检查项目。您需要调用ListView.SetItemChecked(selectedItemIndex,true)。 Link
EDIT。
抱歉,我错了。您在内部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;
}
}
}