2015-04-12 49 views
0

我正在使用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

編輯。

對不起,我錯了。您在內部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; 
     } 
    } 
} 
+0

謝謝你的回覆。我試過這段代碼,但是在調用base.GetView(不能調用抽象方法)時,在Xamarin Studio中出現錯誤。 –

+0

我讀過你的評論,checked = true必須在ListView上設置,而不是在每個項目上,所以我將此代碼添加到活動(不是適配器):myListView.SetItemChecked(chosenIndex,true); –

+0

所以你的回答確實幫助我解決了這個問題:-)你想改變答案中的代碼,還是它真的適合你?如果我確信代碼片段也是正確的,我很高興將其標記爲正確的答案。 –

相關問題