在每个按钮上,单击数据将以意外方式添加到列表视图中。数据在列表视图中重复

时间:2013-11-11 07:24:59

标签: dot42

[Activity]
public class MainActivity : Activity
{
  public string[] items = new string[100];    // string to store data from editText
  int i =0;
  ArrayAdapter<string > adapter;
  protected override void OnCreate(Bundle savedInstance) 
  {
    base.OnCreate(savedInstance);
    SetContentView(R.Layouts.MainLayout);

    var btn1= FindViewById <Button> (R.Ids.btn1);
    btn1.Click += AddItem;    // calls a function on button click to add data to listview
  }

  public void AddItem(object sender,EventArgs eventargs)
  {
    try
    {
      var et1 = FindViewById <EditText>(R.Ids.et1);
      items[i] = et1.Text.ToString();
      i++;
      view();    //to add data to listview
    }

    catch(Exception ex)
    {
      error(ex.ToString());
    }
  }

  public void view ()
  {
    adapter = new ArrayAdapter<string>(GetApplicationContext(),Android.R.Layout.Simple_list_item_1,items);
    ListView listview = FindViewById<ListView>(R.Ids.listview1);
    listview.SetAdapter(adapter);
    listview.SetTextFilterEnabled(true);

    }
  }

1 个答案:

答案 0 :(得分:1)

您不应该从view()调用AddItem,因为视图中的所有代码都是初始化代码。将其重命名为initList左右,然后从OnCreate调用它。

您也不需要items(或i)。只需将字符串添加到adapter

- 编辑

[Activity]
public class MainActivity : Activity
{
   private ArrayAdapter<string> adapter;

   protected override void OnCreate(Bundle savedInstance)
   {
      base.OnCreate(savedInstance);
      SetContentView(R.Layouts.MainLayout);

      ListView list = FindViewById<ListView>(R.Ids.list);
      adapter = new ArrayAdapter<string>(this, Android.R.Layout.Simple_list_item_1);
      list.SetAdapter(adapter);

      Button button = FindViewById<Button>(R.Ids.button);
      button.Click += button_Click;
   }

   void button_Click(object sender, EventArgs e)
   {
      EditText text = FindViewById<EditText>(R.Ids.text);
      adapter.Add(text.Text.ToString());
   }
}