RecyclerView:
優勢:
提供了一種插拔式的體驗,高度解耦,異常靈活
用法:
1.經過佈局管理器LayoutManager控制其顯示方式
2.經過ItemDecoration控制Item的間隔(可繪製)
3.經過ItemAnimator控制Item的增刪動畫
首先在build.gradle中添加依賴:android
implementation 'com.android.support:recyclerview-v7:28.0.0'
版本號因人而異,個人是28,而後創建item_view.xml,設置其子項顯示的佈局:app
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="80dp"> <TextView android:id="@+id/textView" android:gravity="center" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.constraint.ConstraintLayout>
設置activity_main.xml:ide
<?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" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.fitsoft.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.constraint.ConstraintLayout>
MainActivity:函數
package com.fitsoft; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recycler_view); //設置線性佈局管理器 LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(linearLayoutManager); //設置適配器 MyAdapter myAdapter = new MyAdapter(); recyclerView.setAdapter(myAdapter); } private class MyAdapter extends RecyclerView.Adapter{ MyViewHolder viewHolder; @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { //綁定佈局 View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view, viewGroup, false); //綁定佈局裏面的元素 //因爲RecyclerView.ViewHolder是靜態抽象類,不能實例化,只能新建一個類來繼承 viewHolder = new MyViewHolder(itemView); return viewHolder; } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { //這裏的viewHolder其實就是咱們新建的MyViewHolder類的一個對象,這裏進行強制轉換 //數據的處理都在這個函數裏面 ((MyViewHolder) viewHolder).textView.setText("編號:"+i); } @Override public int getItemCount() { //返回子項的個數 return 30; } private class MyViewHolder extends RecyclerView.ViewHolder{ //繼承這個靜態抽象類,使之能夠被綁定 private TextView textView; MyViewHolder(@NonNull View itemView) { super(itemView); textView = itemView.findViewById(R.id.textView); } } } }
註釋很詳細。
效果圖:佈局