簡體   English   中英

Android-使用布爾值在“自定義ListView”中選中復選框

[英]Android - Check checkbox in 'Custom ListView' using Boolean

我在C#Android應用程序中有一個自定義listview,每一行包含一個textview,ImageView和一個復選框。 單擊Listview項時,我想使用bool值檢查該行的項目復選框。

MainActivity.cs

List<TableList> list = = new List<TableList>();
list.Add(new TableList("Germany"));
list.Add(new TableList("France"));
list.Add(new TableList("Finland"));
listView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs e)
    {
        string selected = t.Name;
        if (selected == "France")
        {
             Class1.bl = false; // Check the proper checkbox for France row
        }
    };

Class1.bl是設置為true的靜態公共布爾

ListView的ListAdapter和ListClass:

public class ListAdapter : BaseAdapter<TableList>
{
List<TableList> items;
Activity context;
public ListAdapter(Activity context, List<TableList> items)
    : base()
{
    this.context = context;
    this.items = items;
}
public override long GetItemId(int position)
{
    return position;
}
public override TableList 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)
{
    var item = items[position];
    View view = convertView;
    if (view == null) // no view to re-use, create new
        view = context.LayoutInflater.Inflate(Resource.Layout.CoinList, null);
    view.FindViewById<TextView>(Resource.Id.CoinName).Text = item.Name;
     view.FindViewById<ImageView>(Resource.Id.imageView1).SetImageResource(Resource.Drawable.n);

    if (Class1.bl == false)
        {
            view.FindViewById<CheckBox>(Resource.Id.checkBox1).Checked = true;
            Class1.bl = true;
        }
        else
        {
            view.FindViewById<CheckBox>(Resource.Id.checkBox1).Checked = false;
        }
    return view;
  }
 }
public class TableList
{
public string Name;
public TableList(string Name)
{
    this.Name = Name;
}
}

當我運行上面的代碼並選擇“法國”時,會檢查ChechBox是否為法國,但是當我檢查其他項目(如德國)時,不會選中“德國的ChechBox ”。 為什么會這樣,我該如何解決?

我在您的TableList類中添加了布爾值:

//I add the bool in this class, so you can change the CheckBox's state by your Data Source
//That means that your CheckBox's state based upon your Data Source.
public class TableList : Java.Lang.Object
{
    public TableList(string name, bool b)
    {
        this.Name = name;
        this.bl = b;
    }
    public string Name { get; set; }
    public bool bl { get; set; }
}

我還在github上提供了演示, 是結果gif。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM