[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);
}
}
答案 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());
}
}