listview没有使用notifydatasetchanged()调用进行更新

tr_*_*est 15 android listview android-arrayadapter

这是我的代码

listview =(ListView) findViewById(R.id.lv1);


    ArrayList<SClass> Monday = new ArrayList<SClass>();

    SClass s1=new SClass();
    s1.sName="samp";
    s1.salary=1000;
    Monday.add(s1);
    temp=Monday;
    adapter = new CustomAdap(this, temp);
    listview.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常.但是当我将代码更改为此时

    listview =(ListView) findViewById(R.id.lv1);


    adapter = new CustomAdap(this, temp);

    SClass s1=new SClass();
    s1.sName="samp";
    s1.salary=1000;
    Monday.add(s1);
    temp=Monday;

    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

Listview没有显示任何内容.问题是什么?

lou*_*uie 18

看起来您正在更改初始化适配器的集合.我会以这种方式更改您的代码:

// initial setup
listview =(ListView) findViewById(R.id.lv1);
ArrayList<SClass> Monday = new ArrayList<SClass>();
adapter = new CustomAdap(this, Monday);
listview.setAdapter(adapter);

// change your model Monday here, since it is what the adapter is observing
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
Monday.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

请注意,如果您的CustomAdap是ArrayAdapter的子类,您也可以这样做

// change your array adapter here
SClass s1=new SubjectClass();
s1.sName="samp";
s1.salary=1000;
adapter.add(s1);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

编辑:由于你的评论,我现在更了解你想做什么.您可能希望让适配器将其内容替换为您的不同ArrayLists.我会让你的CustomAdap成为ArrayAdapter的子类.

然后你可以这样使用它:

// replace the array adapters contents with the ArrayList corresponding to the day
adapter.clear();
adapter.addAll(MONDAY);

// notify the list that the underlying model has changed
adapter.notifyDataSetChanged();
Run Code Online (Sandbox Code Playgroud)

  • 您的CustomAdap必须子类化ArrayAdapter,其中包括`clear`和`addAll`.类似`public class CustomAdap的扩展ArrayAdapter <SClass>`.请参阅http://developer.android.com/reference/android/widget/ArrayAdapter.html以供参考. (2认同)

MKJ*_*ekh 5

为什么它在第一个代码中有效?

---因为您正在将值设置为tempList并将其传递给它adapter并将其显示出来listview.

为什么不在第二个代码中工作?

---因为在将值设置为temp
之前将适配器设置为temp,所以当您将新值设置为temp时,适配器类可能无法获取更新的值.因为temp不是公共的或不是类级别的static ..将temp声明放在root级别并尝试.

如果您收到任何警告,请尽可能多地显示您的完整代码和Logcat.