Android - 选中'自定义列表视图'使用布尔

时间:2018-05-28 11:55:59

标签: c# android visual-studio listview xamarin

我的C#Android应用程序中有自定义列表视图,每行包含一个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。为什么这样,我该如何解决?

1 个答案:

答案 0 :(得分:0)

我在你的TableList课程中添加了bool:

//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上提供演示,而here是结果gif。