避免重复列表视图

时间:2016-10-22 11:20:18

标签: java android listview android-arrayadapter

我正在使用此代码段填充列表视图,但是需要检查列表视图中是否已经存在从textviw中获取的值,是否有人知道此问题的良好做法?

 tv.setText(count+" | "+"id: "+uid+"  Sak: "+Sak+"  atqa: "+atqa );
    count++;
    int k=sp.getCount();
    String a1[]=new String[k+1];
    for(int i=0;i<k;i++)
        a1[i]=sp.getItemAtPosition(i).toString();
    a1[k]=tv.getText().toString();
    ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);



    sp.setAdapter(ats);

2 个答案:

答案 0 :(得分:0)

您不需要使用AdapterView#getItemAtPosition(int)来获取与行项关联的数据,因为ArrayAdapter本身允许您#getItem(int)和#getCount()。

所以要获得完整的数组支持listview。做:

String newItem = "Item to insert";
for(int i=0; i<adapter.getCount(); i++){
   String foo = (Object) adapter.getItem(i);
   if (foo.equals(newItem)){
    return; // do not add
   }
}
adapter.add(newItem); // add it 

答案 1 :(得分:0)

    int k=sp.getCount();
    String a1[]=new String[k+1];

        for (int i = 0; i < k; i++) {
            a1[i] = sp.getItemAtPosition(i).toString();
            Log.e("test", "test" + a1[i].toString());
            Log.e("test", "orig" + " | " + "id: " + uid + "  Sak: " + Sak + "  atqa: " + atqa);

            String foo = (" | " + "id: " + uid + "  Sak: " + Sak + "  atqa: " + atqa);
            if (foo.equals(a1[i].toString())) {
                Log.e("eqal", "equal");
                return;


            }
        }

    a1[k]=tv.getText().toString();
    ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
    Log.e("test","test"+ats.getItem(k));


    sp.setAdapter(ats);