ListView笔记

本文是 郭霖. 第一行代码[M]. 人民邮电出版社, 2014. 第三章第五节的笔记

最简单的实现:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidstudy.MainActivity">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</android.support.constraint.ConstraintLayout>
public class MainActivity extends AppCompatActivity {
    private String[] data={"apple","banana","Orange","djkf","apple","banana","Orange","djkf",
            "apple","banana","Orange","djkf","apple","banana","Orange","djkf"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, data);
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(arrayAdapter);
    }
}
我们需要借助适配器将数组传递给listView,这里使用ArrayAdapter。 # 定制ListView的界面

实体类:

public class Fruit {
    private String name;
    private int imgId;

    public Fruit(String name, int imgId) {
        this.name = name;
        this.imgId = imgId;
    }

    public String getName() {
        return name;
    }

    public int getImgId() {
        return imgId;
    }
}

ListView 子项的自定义布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/fruit_text"
        android:layout_gravity="center_vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

创建一个自定义Adapter,继承自ArrayAdapter,并将泛型指定为Fruit类:

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;

    public FruitAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Fruit fruit = getItem(position);// 获取当前的Fruit实例
        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
        TextView fruitText = (TextView) view.findViewById(R.id.fruit_text);
        fruitImage.setImageResource(fruit.getImgId());
        fruitText.setText(fruit.getName());
        return view;
    }
}

重写的getView方法在每个子项被滚动到屏幕内的时候会被调用,使用LayoutInflater加载传入的子布局,第三个参数false表示只让在父布局中声明的layout属性生效,而不为这个View添加父布局,然后调用view的findViewById方法分别获取到imageView和TextView实例,分别设置显示的图片和文字,最后将布局返回。

public class MainActivity extends AppCompatActivity {
    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);

        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(MainActivity.this, fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initFruits() {
        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }
}

在MainActivity里面将fruitList传入FruitAdapter对象,并将FruitAdapter作为适配器传递给listView。

# 提升ListView的运行效率 这里的ListView效率太低,因为FruitAdapter的getView方法中每次都将布局重新加载了一遍,当listView快速滚动的时候就会影响性能。 ```java @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Log.i("FruitAdapter","子项"+position+"被划入到屏幕内"); Fruit fruit = getItem(position);// 获取当前的Fruit实例 View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image); TextView fruitText = (TextView) view.findViewById(R.id.fruit_text); fruitImage.setImageResource(fruit.getImgId()); fruitText.setText(fruit.getName()); return view; } ``` 使用Log调试发现,每次有子项被划入到屏幕内的时候就会被调用。 ``` 04-09 15:45:08.750 8227-8227/com.androidstudy I/FruitAdapter: 子项7被划入到屏幕内 04-09 15:45:09.016 8227-8227/com.androidstudy I/FruitAdapter: 子项8被划入到屏幕内 04-09 15:45:09.644 8227-8227/com.androidstudy I/FruitAdapter: 子项9被划入到屏幕内 04-09 15:45:11.799 8227-8227/com.androidstudy I/FruitAdapter: 子项1被划入到屏幕内 04-09 15:45:12.138 8227-8227/com.androidstudy I/FruitAdapter: 子项0被划入到屏幕内 04-09 15:45:20.833 8227-8227/com.androidstudy I/FruitAdapter: 子项7被划入到屏幕内 04-09 15:45:20.908 8227-8227/com.androidstudy I/FruitAdapter: 子项8被划入到屏幕内 04-09 15:45:21.010 8227-8227/com.androidstudy I/FruitAdapter: 子项9被划入到屏幕内 ``` 我们可以使用getView()里面的convertView将之前加载好的布局进行缓存,以便之后可以重用。 ```java @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Log.i("FruitAdapter","子项"+position+"被划入到屏幕内"); Fruit fruit = getItem(position);// 获取当前的Fruit实例 View view; if (convertView == null) { view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); Log.i("FruitAdapter","加载子项"+position); } else { view = convertView; Log.i("FruitAdapter","重用子项"+position); } ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image); TextView fruitText = (TextView) view.findViewById(R.id.fruit_text); fruitImage.setImageResource(fruit.getImgId()); fruitText.setText(fruit.getName()); return view; } ```
04-09 15:58:14.949 21370-21370/com.androidstudy I/FruitAdapter: 子项0被划入到屏幕内
04-09 15:58:14.954 21370-21370/com.androidstudy I/FruitAdapter: 加载子项0
04-09 15:58:14.955 21370-21370/com.androidstudy I/FruitAdapter: 子项1被划入到屏幕内
04-09 15:58:14.955 21370-21370/com.androidstudy I/FruitAdapter: 重用子项1
04-09 15:58:14.956 21370-21370/com.androidstudy I/FruitAdapter: 子项2被划入到屏幕内
04-09 15:58:14.957 21370-21370/com.androidstudy I/FruitAdapter: 重用子项2
04-09 15:58:14.958 21370-21370/com.androidstudy I/FruitAdapter: 子项3被划入到屏幕内
04-09 15:58:14.958 21370-21370/com.androidstudy I/FruitAdapter: 重用子项3
04-09 15:58:14.959 21370-21370/com.androidstudy I/FruitAdapter: 子项4被划入到屏幕内
04-09 15:58:14.959 21370-21370/com.androidstudy I/FruitAdapter: 重用子项4

由此可见,对于同样的布局,只需要加载一次,之后重用就可以了。
虽然不会重复的去加载布局,但是每次getView方法中还是会调用View的findViewById方法获取一次控件的实例,我们可以借助ViewHolder来对这部分性能进行优化。

public class FruitAdapter extends ArrayAdapter<Fruit> {
    private int resourceId;

    public FruitAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Fruit> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Log.i("FruitAdapter","子项"+position+"被划入到屏幕内");
        Fruit fruit = getItem(position);// 获取当前的Fruit实例
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            Log.i("FruitAdapter","加载子项"+position);
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            viewHolder.fruitText = (TextView) view.findViewById(R.id.fruit_text);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder)view.getTag();// 重新获取ViewHolder
            Log.i("FruitAdapter","重用子项"+position);
        }
        
        viewHolder.fruitImage.setImageResource(fruit.getImgId());
        viewHolder.fruitText.setText(fruit.getName());
        return view;
    }

    class ViewHolder{
        ImageView fruitImage;
        TextView fruitText;
    }
}

基于BaseAdapter

public class FruitBaseAdapter extends BaseAdapter
{
    Context mContext;
    List<Fruit> mDatas;
    private int mItemLayoutId;

    public FruitBaseAdapter(Context mContext, int mItemLayoutId, List<Fruit> mDatas) {
        this.mContext = mContext;
        this.mDatas = mDatas;
        this.mItemLayoutId = mItemLayoutId;
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Fruit fruit = (Fruit)getItem(position);
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(mContext).inflate(mItemLayoutId, parent, false);
            Log.i("FruitBaseAdapter","加载子项"+position);
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            viewHolder.fruitText = (TextView) view.findViewById(R.id.fruit_text);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder)view.getTag();// 重新获取ViewHolder
            Log.i("FruitBaseAdapter","重用子项"+position);
        }
        viewHolder.fruitImage.setImageResource(fruit.getImgId());
        viewHolder.fruitText.setText(fruit.getName());
        return view;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值