ArrayAdapter替换listview中的所有值

时间:2014-09-02 19:19:15

标签: android listview xamarin xamarin.android android-arrayadapter

我有一个名为AddItemArrayAdapter的类,它使用按钮和Main.axml中的EditText填充一个列表视图。但是当我添加一个新项目时,所有行都会收到新值。

AddItemArrayAdapter.cs

public class AddItemArrayAdapter: ArrayAdapter<string>
{
    List<string> _ListOfText = new List<string> ();
    Context _Context;
    int _Resorce;
    string lastText;


    public AddItemArrayAdapter (Context context, int resource, List<string> ListOfText) 
        : base(context,resource, ListOfText)
    {
        this._Context = context;
        this._Resorce = resource;
        this._ListOfText =  ListOfText;
    }

    public string GetLastItem()
    {
        lastText = _ListOfText[(_ListOfText.Count - 1)];

        return lastText;
    }

    public override View GetView (int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflate = (LayoutInflater)_Context.GetSystemService (Context.LayoutInflaterService);

        View rowView;

        rowView = inflate.Inflate (Resource.Layout.newTextFromEdit , parent, false);

        TextView textView = rowView.FindViewById<TextView> (Resource.Id.singleText);

        textView.Text = GetLastItem();

        return rowView;
    }
}

按钮单击MainActivity.cs:

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

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

    if(!(textFromEditText.Equals(string.Empty)))
    {
        ListWhitText.Add(textFromEditText);

        try
        {
            _ListViewWhitTexts.Adapter = new AddItemArrayAdapter (this,Resource.Layout.newTextFromEdit , ListWhitText);

           catch (Exception ex)         
           {
              Console.WriteLine(ex.Message);
           }
        }

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

1 个答案:

答案 0 :(得分:0)

如果您在GetView()中查看AddItemArrayAdapter.cs的实施情况,请注意您致电textView.Text = GetLastItem();

当适配器构建列表时,为每一行调用

GetView()。因此,每一行都将使用GetLastItem();

中的文字

GetView()的第一个参数是一个名为position的int,它是当前为其构建UI的列表中的项目。将上面的行更改为此

  

textView.Text = _ListOfText [position];

并且每一行都将查找字符串数组的正确索引。