notifyDataSetChanged()不适用于baseAdapter和自定义ListView

时间:2018-06-25 22:45:59

标签: android listview

我需要ListView逐行显示数据

因此,这是代码示例:

public class ClassName extends AppCompatActivity {
  ListView _listView;
  List <Info> myList;
  CustomAdapterClass myAdapted;

 protected void onCreate(Bundle savedInstanceState) {    
     super.onCreate(savedInstanceState);
        setContentView(R.layout.myActivity);
        _listView = (ListView) findViewById(R.id.viewListView);
        myList= new ArrayList<>();

        myAdapted = new CustomAdapterClass();
        _listView.setAdapter(myAdapted);
        CallingSomeMethodToGetData (SomeData myData);

                  DoThisInBackground{ 
                    myList.clear();
                    Info info;
                    int k=0;
                    for (SomeData  object: myData){
                       Log.i("k:", String.valueOf(k));
                       k++;
                        info = new Info();
                        info.addData(object.getdata());
                        myList.add(info)
                        myAdapted.notifyDataSetChanged();
                        SystemClock.sleep(400);
                    }
                }
    }  

 class  CustomAdapterClass extends BaseAdapter{
        @Override
        public int getCount() {
            return myList.size();
        }
        @Override
        public Object getItem(int i) {
            return myList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            Log.i("I: ", String.valueOf(i));
            view = getLayoutInflater().inflate(R.layout.custom_list_view, null);
            TextView  _textView = (TextView)view.findViewById(R.id.name_CustomView);

             _textView .setText(mysList.get(i).getMyData());

            return view;
        }
    }

    }

我得到的行为是直到所有数据都加载到ListView之前,myList才更新。

换句话说,我在日志中为每个k打印info,并且在加载所有数据后,I开始在日志中打印 我试图尽量减少代码,以便可以阅读

2 个答案:

答案 0 :(得分:0)

  

NotifyDataSetChanged   应该从UI线程调用。

此外,您可以考虑使用RecyclerView以获得更好的性能。它还暴露了

  

public final void notifyItemChanged(int position,@Nullable Object有效负载)

这样,您也可以仅更新特定项目。

答案 1 :(得分:0)

尝试此代码.. 定义适配器构造器.. 下面的代码定义到适配器中。.

    private Context context;
    private List<Info>mylist=new ArrayList<>();

    public CustomAdapterClass(Context context, List<Info> mylist) {
        this.context = context;
        this.mylist = mylist;
    }

获取数据后,定义适配器并绑定到列表视图

    myAdapted = new CustomAdapterClass(this,mList); // if fragement then used getActivity().
    _listView.setAdapter(myAdapted);


                    myAdapted.notifyDataSetChanged();