在Listview中添加新项目已填充应用程序的开头

时间:2014-10-17 18:52:37

标签: android listview android-listview xamarin

使用ListFragment和BaseAdapter在应用程序的开头填充My ListView。在布局中,我有一个用于添加新项目的按钮,但是当我在ListView中添加新项目时,项目将被删除。

我的ListFragment.cs:

public class TabItems : ListFragment
{
    AdapterItems _Adaptador;

    public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.Inflate (Resource.Layout.Items, null);

        ListView listView = (ListView)view.FindViewById (Android.Resource.Id.ListItems);

        _Adaptador = new AdapterItems(this.Activity,
                                          WebService.ReturnListItems());

        listView.Adapter = _Adaptador;

        return view;
    }

    public override void OnListItemClick(ListView l, View v, int position, long id)
    {
        Bundle bundle = new Bundle();

        Intent activity = new Intent(v.Context, typeof(ChatActivity));

        int value = (int)l.Adapter.GetItem(position);

        bundle.PutInt("value", value);

        activity.PutExtras(bundle);

        StartActivity(activity);
   }
}

我的Activity.cs

List<string> _List = new List<string>();

    ArrayAdapter<string> _Adapter;
    ListView _ListView;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.TelaChat);

        UtilPop.CreateListViewWithItems(); // populate listview in start

        _ListView = FindViewById<ListView>(Resource.Id.ListItems);

        ImageButton btnAddItem = FindViewById<ImageButton>(Resource.Id.botaoAddItem);

        btnAddItem.Click += btnAddItem_Click;
    }

    void btnAddItem_Click(object sender, EventArgs e)
    {
        EditText edttxItem = FindViewById<EditText>(Resource.Id.ItemName);

        AddItem(edttxMensagem.Text);
    }

    //add new item in listview
     private void AddItem(string itemName)
    {
        _List.Add(itemName);

        _Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1,    _List);

        _ListView.Adapter = _Adapter;

        _ListView.DeferNotifyDataSetChanged();

    }

0 个答案:

没有答案