Search code examples
c#androidlistviewxamarinbaseadapter

ListView with BaseAdapter, show only one row


I created a class called AddItemBaseAdapter that adds a new row in the ListView. The problem is that when adding a new row, the previous row is deleted. To add a new row I have a editTex and a button on Main.axml. For this case it is better to use ArrayAdapter or BaseAdapter continue using?

AddItemBaseAdapter.cs:

public class AddItemBaseAdapter: BaseAdapter<string> 
{
    string textReceivedEditText;
    Activity context;

    public AddItemBaseAdapter(Activity context, string textReceivedEditText) : base()
    {
        this.context = context;
        this.textReceivedEditText = textReceivedEditText;
    }

    public override long GetItemId(int position){

        return position;
    }

    public override string this[int position] {  
        get { return textReceivedEditText; }
    }

    public override int Count {
        get { return 1; }
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View view = convertView; // re-use an existing view, if one is available

        if (view == null)
                view = context.LayoutInflater.Inflate (Resource.Layout.newText, null);

        view.FindViewById<TextView>(Resource.Id.singleText).Text = textReceivedEditText;

        return view;
    }
}

OnClick in MainActivity.cs

btnAddNewRow.Click += delegate(object sender, EventArgs e) {

            string textFromEditText = FindViewById<EditText> (Resource.Id.editText).Text;

            if(!(textFromEditText.Equals(string.Empty)))
            {
                _HistoryList = FindViewById<ListView>(Resource.Id.TextHistoryList);

                _HistoryList.Adapter = new AddItemBaseAdapter(this, textFromEditText);
            }

            FindViewById<EditText> (Resource.Id.editText).Text = string.Empty;

};


Solution

  • You are creating an entirely new AddItemBaseAdapter every time the button is clicked.

    _HistoryList.Adapter = new AddItemBaseAdapter(this, textFromEditText);

    Your adapter does not even have the capacity to store more than one item as it stands now. Perhaps try using (or at least studying) the ArrayAdapter class to start. Then if you require futher functionality beyond that, you can extend it or write your own adapter.