1
[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);

    }
  }
4

1 回答 1

1

您不应该调用view()from,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());
   }
}
于 2013-11-11T08:51:25.410 回答