How to load the Listview “smoothly” in android

前端 未结 5 2009
盖世英雄少女心
盖世英雄少女心 2020-11-30 20:09

I load data from Cursor to listview, but my Listview not really display \"smooth\". The data change when I drag up and down on the scollbar in my ListView. And some items lo

5条回答
  •  有刺的猬
    2020-11-30 20:12

    ListView is a tricky beast.

    Your second question first: you're seeing duplicates because ListView re-uses Views via convertView, but you're not making sure to reset all aspects of the converted view. Make sure that the code path for convertView!=null properly sets all of the data for the view, and everything should work properly.

    You'll want your getView() method to look roughly like the following if you're using custom views:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final MyCustomView v = convertView!=null ? (MyCustomView)convertView : new MyCustomView();
        v.setMyData( listAdapter.get(position) );
        return v;
    }
    

    If you're not using your own custom view, just replace the call to new MyCustomView() with a call to inflater.inflate(R.layout.my_layout,null)

    As to your first question, you'll want to watch Romain's techtalk on ListView performance here: http://code.google.com/events/io/sessions/TurboChargeUiAndroidFast.html

    From his talk and in order of importance from my own experience,

    • Use convertView
    • If you have images, don't scale your images on the fly. Use Bitmap.createScaledBitmap to create a scaled bitmap and put that into your views
    • Use a ViewHolder so you don't have to call a bunch of findViewByIds() every time
    • Decrease the complexity of the views in your listview. The fewer subviews, the better. RelativeLayout is much better at this than, say, LinearLayout. And make sure to use if you're implementing custom views.

提交回复
热议问题