海创软件组--20200614--ListView和RecyclerView

AS提供的ListView和RecyclerView是我们常常要用到的,它两的不同之处是值得研究的
下面先看看ListView
ListView适用于展示一些简单的文本、图片,以滚动的方式查看每个子项
以一个展示水果为例
海创软件组--20200614--ListView和RecyclerView_第1张图片
水果的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp" />

</LinearLayout>

简单的水果类

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

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }

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

主逻辑

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);
        initFuits();//初始化水果数据
        FruitAdapter adapter = new FruitAdapter(MainActivity.this, R.layout.fruit_item, fruitList);//适配数据
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        
    private void initFuits(){
        for (int i = 0; i < 5 ; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.aaa);
            fruitList.add(apple);
            Fruit pear = new Fruit("pear", R.drawable.aaa);
            fruitList.add(pear);
            Fruit Orange = new Fruit("Orange", R.drawable.aaa);
            fruitList.add(Orange);
            Fruit Banana = new Fruit("Banana", R.drawable.aaa);
            fruitList.add(Banana);

        }
    }
}

数据无法直接传入ListView 需要使用Adapter适配器把数据适配好 再装入listView中
所以我们需要自定义一个水果数据的适配器

//记得继承ArrayAdapter
public class FruitAdapter extends ArrayAdapter <Fruit> {

    private int resourceId;

    public FruitAdapter(@NonNull Context context, int textViewResourceId,
                            @NonNull List<Fruit> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;  //拿到传入过来自己建立的fruit_item的Id
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Fruit fruit = getItem(position);//获取当前项的Fruit实例
        View view;
        ViewHolder viewHolder;
//   在加载布局的时候先判断,会提升效率,不用每次重复加载
//    只要过执行一次getView,返回的View就会存到converView,所以以后view就不需要重复加载,控件也是同样的道理
        if (convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.fruitImage = view.findViewById(R.id.fruit_image);
            viewHolder.fruitName = view.findViewById(R.id.fruit_name);
            view.setTag(viewHolder);//将ViewHolder存储在View中
        }else {
            view = convertView;
            viewHolder = (ViewHolder)view.getTag();
        }
        viewHolder.fruitImage.setImageResource(fruit.getImageId());
        viewHolder.fruitName.setText(fruit.getName());
//从fruit_item的id中获得整个fruit_item视图    如果是true的话,该布局就只能在
//                                其父布局生效也就是LinearLayout,这样的话就不能在ListView中用了
//这是没有进行缓存的,快速滑屏会重复加载布局效率会很低
//        View view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
//        ImageView fruitImage = view.findViewById(R.id.fruit_image);
//        TextView fruitName = view.findViewById(R.id.fruit_name);
//        fruitImage.setImageResource(fruit.getImageId());
//        fruitName.setText(fruit.getName());
        return view;
    }
}

//利用ViewHolder来缓存属性,使其不用每次重复获取
class ViewHolder{
    ImageView fruitImage;
    TextView fruitName;
}

每次滚动时都会调用getView()把布局加载到每个子项,这里要用到一些技巧去提高效率,不然每次重复获得同样的控件效率会很低
看上去ListView是很简单,但是它挺有局限性的,只能竖着滑动

下面我们来看看RecycleView,它有着强大的功能,不仅可以竖向滑动,也可以横向滑动,而且还可以瀑布式的滚动
竖向
海创软件组--20200614--ListView和RecyclerView_第2张图片
横向
海创软件组--20200614--ListView和RecyclerView_第3张图片海创软件组--20200614--ListView和RecyclerView_第4张图片

瀑布式
海创软件组--20200614--ListView和RecyclerView_第5张图片
它的布局文件和ListView是很相似的

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">

    <ImageView
        android:id="@+id/fruit_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:id="@+id/fruit_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginTop="10dp" />

</LinearLayout>

另外水果类是一样的,我们这就不需要多写了

主逻辑

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);
        initFuits();//初始化水果数据
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
//  瀑布流动  交错网格布局管理器 第一个参数会把布局分为3列;第二个用于指定布局的排列方向
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this);//创建一个线性布局管理者LinearLayoutManager
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);//横向滚动时改为水平
        recyclerView.setLayoutManager(layoutManager);//用于指定recyclerView的布局方式
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFuits() {
        for (int i = 0; i < 5; i++) {
            Fruit apple = new Fruit(getRandomlengthName("Apple"), R.drawable.aaa);
            fruitList.add(apple);
            Fruit pear = new Fruit(getRandomlengthName("pear"), R.drawable.aaa);
            fruitList.add(pear);
            Fruit Orange = new Fruit(getRandomlengthName("Orange"), R.drawable.aaa);
            fruitList.add(Orange);
            Fruit Banana = new Fruit(getRandomlengthName("Banana"), R.drawable.aaa);
            fruitList.add(Banana);

        }
    }

    //小技巧 增加字符串长度
    private String getRandomlengthName(String name) {
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < length; i++) {
            builder.append(name);
        }
        return builder.toString();
    }
}

代码块的注释已经非常清晰了
另外这里不同的滚动方式可以setLayoutManager()来设置,如果是LinearLayoutManager它默认是竖向的

同样的我们需要自定义水果数据适配器

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private List<Fruit> mFruitList;

//从缓存中拿到控件
    static class ViewHolder extends RecyclerView.ViewHolder{
        View fruitView;
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View view){    //这个View就是RecycleView子项的最外层布局在下面的方法中能够传来,感觉像是使用了多态
            super(view);
            fruitView = view;
            fruitImage = view.findViewById(R.id.fruit_image);
            fruitName = view.findViewById(R.id.fruit_name);
        }
    }

    public FruitAdapter(List<Fruit> mFruitList) {
        this.mFruitList = mFruitList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    @Override
    public int getItemCount() {
        return mFruitList.size();
    }
}

这里我们需要继承的是RecyclerView.Adapter并指定泛型
要重写三个方法
其中onCreateViewHolder()只会执行一次,使得控件只需要获取一次,然后缓存在ViewHolder中用于提高效率,和ListView有异曲同工之妙
onBindViewHolder()每次滑动子项时都会得到执行,用于加载控件的内容,和ListView的getView()相对应
getItemCount()只需要返回子项的个数就行了
虽然RecyclerView的代码比较多,但他比ListView逻辑更加清晰

总之ListView和RecyclerView的最大不同在于RecyclerView的滚动方式更加丰富,可以适用于多种不同场景。

你可能感兴趣的:(海创软件组--20200614--ListView和RecyclerView)