简体   繁体   English

ListView不会在notifyDataSetChanged上刷新

[英]ListView doesn't refresh on notifyDataSetChanged

ListView doesn't seem to refresh when notifyDataSetChanged(); notifyDataSetChanged();时, ListView似乎没有刷新notifyDataSetChanged(); is called, but does refresh when its adapter gets set again. 会被调用,但是当适配器再次设置时会刷新。

In my Activity onCreate I initialize my ListView and my adapter. 在我的Activity onCreate我初始化了ListView和适配器。 Then I have this Hanler that checks for new values every second. 然后,我有这个Hanler检查一次新值。 listview.setAdapter(arrayAdapter); works but arrayAdapter.notifyDataSetChanged(); 工作,但arrayAdapter.notifyDataSetChanged(); doesn't do anything. 什么也没做

Here is the code: 这是代码:

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

                     lv = (ListView) findViewById(R.id.listView1);

            arrayAdapter = new ArrayAdapter<Integer>(this,android.R.layout. simple_list_item_1, myIntegers);
            lv.setAdapter(arrayAdapter);
    }

    private Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                if (msg.what == DIS){
                    handler.sendEmptyMessageDelayed(DIS, 1000);
                    if(!refresh()){
                        handler.removeMessages(DIS);
                    }
                }
            }
        };

   public boolean refresh(){

        if(ports.isEmpty()){
            return false;
        }else{
            listview.setAdapter(arrayAdapter); //WORKS
    arrayAdapter.notifyDataSetChanged(); // DOESN'T WORK
            return true;
            }
    }

So I was wondering how to make that work with notifyDataSetChanged , because I read that it is the right way to do it, and anyway even if the setAdapter does work it makes my listview jump to beginning every time it refreshes it. 所以我想知道如何使用notifyDataSetChanged来实现该notifyDataSetChanged ,因为我读到这是正确的方法,无论如何,即使setAdapter确实起作用,它也会在每次刷新它时使我的列表视图跳转到开始。

EDIT: 编辑:

To clarify things, I am adding more values to myIntegers. 为了澄清问题,我向myIntegers添加了更多值。

Try instead adding the values using the adapter.add() method. 请尝试使用adapter.add()方法添加值。 I dont think you can modify the array that was used to create the adapter and then expect it to hold an updated instance to update the views from. 我不认为您可以修改用于创建适配器的数组,然后期望它包含更新的实例以从中更新视图。 Best of Luck! 祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM