day09:RecyclerView基礎(chǔ)

今天說(shuō)一下RecyclerView的基礎(chǔ),還及得我們講過(guò)ListView嗎,其實(shí)今天說(shuō)的內(nèi)容就是ListView的進(jìn)化版,我個(gè)人覺(jué)得還是RecyclerView好用,而且RecyclerView的功能比較強(qiáng)大,可以實(shí)現(xiàn)ListView的功能,而它實(shí)現(xiàn)的功能ListView有的不能實(shí)現(xiàn)。今天我做了一個(gè)recyclerview最簡(jiǎn)單的用法。先看一下效果圖。

image

看這個(gè)效果圖是不是有點(diǎn)像ListView,對(duì),我布局代碼還是采用原來(lái)的代碼,為了區(qū)分,我加了分割線?,F(xiàn)在看一下步驟吧:

1、添加依賴庫(kù)文件(在app/build.gradle添加)。implementation'com.android.support:recyclerview-v7:27.1.1'

2、創(chuàng)建主xml文件。(recyclerview_main.xml)


<?xml version="1.0" encoding="utf-8"?>

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

    android:layout_width="match_parent"

    android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:divider="#ffff0000"

        android:dividerHeight="10dp"

        android:id="@+id/recycler">

</android.support.v7.widget.RecyclerView>

3、創(chuàng)建布局xml文件(我還是用的以前的listview.xml):


<?xml version="1.0" encoding="utf-8"?>

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

    android:layout_width="match_parent"

    android:layout_height="wrap_content">

<ImageView

        android:id="@+id/list_photo"

        android:layout_width="56dp"

        android:layout_height="56dp"

        android:paddingLeft="10dp"

        android:src="@drawable/a1" />

<TextView

            android:id="@+id/list_text"

            android:layout_width="match_parent"

            android:layout_toRightOf="@id/list_photo"

            android:layout_height="56dp"

            android:gravity="center"

            android:textColor="@android:color/holo_red_dark"

            android:textSize="20sp"/>

4、建立一個(gè)class文件(Dongwu.class)

public class Dongwu {
    private String name;
    private int imageId;
    public String getName(){
        return name;
    }

    public int getImageId() {
        return imageId;
    }
   public Dongwu(String name,int imageId){
        this.name=name;
        this.imageId=imageId;
   }
}

5、現(xiàn)在我們還要建立一個(gè)class文件(配置器:RecyclerViewAdapter)

這里我按照我理解的解釋一下,這個(gè)類要實(shí)現(xiàn)三個(gè)方法。

  • onCreateViewHolder()這個(gè)是在View添加畫面,最后返回holder;
  • onBindViewHolder()這個(gè)是在對(duì)布局填充數(shù)據(jù);
  • getItemCount()這個(gè)是返回子項(xiàng)有多少;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
    private List<Dongwu> mDongwu;
    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView dongwuName;
        ImageView dongwuImage;
        public ViewHolder(View View) {
            super(View);
            dongwuImage =(ImageView) View.findViewById(R.id.list_photo);
            dongwuName =(TextView) View.findViewById(R.id.list_text);
        }
    }
    RecyclerViewAdapter(List<Dongwu> dongwu){
        mDongwu=dongwu;
    }
    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {//這個(gè)ViewGroup是一個(gè)容器
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {//根據(jù)position得到具體哪個(gè)子項(xiàng),然后填充數(shù)據(jù)
        Dongwu dongwu= mDongwu.get(position);
        holder.dongwuImage.setImageResource(dongwu.getImageId());
        holder.dongwuName.setText(dongwu.getName());

    }

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

6、建立最后一個(gè)class文件,用來(lái)做各個(gè)class連接和填充實(shí)例(解釋我直接在代碼上寫);

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class RecyclerViewMain extends AppCompatActivity {
    private List<Dongwu> dongwuList = new ArrayList<>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_main);
//定義一個(gè)方法用來(lái)添加實(shí)例
        init();
//通過(guò)ID找到recyclerview
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler);
//recyclerview添加分割線其中VERTICAL_LIST是豎直方向
        recyclerView.addItemDecoration(new DividerItemDecoration(this,
                itemfenge.VERTICAL_LIST));
        DividerItemDecoration divider = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this,R.drawable.fenge));
        recyclerView.addItemDecoration(divider);
//建立一個(gè)布局來(lái)存放recyclerView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
//實(shí)例化方法并和recyclerView建立連接
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(dongwuList);
        recyclerView.setAdapter(adapter);
    }
//添加實(shí)例對(duì)象
    private void init() {
        for(int i=0;i<8;i++){
            Dongwu niu =new Dongwu("老牛",R.drawable.a1);
            dongwuList.add(niu);
            Dongwu hu=new Dongwu("老虎",R.drawable.a2);
            dongwuList.add(hu);
            Dongwu xiong =new Dongwu("黑熊",R.drawable.a3);
            dongwuList.add(xiong);
            Dongwu xiongma =new Dongwu("熊貓",R.drawable.a4);
            dongwuList.add(xiongma);
        }
    }
}

7、建立分割線的特效(這個(gè)是網(wǎng)上找的,這個(gè)特效使用各種recyclerview的方向:水平,網(wǎng)狀,橫向)

public class itemfenge extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int []{
            android.R.attr.listDivider
    };
    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
    private Drawable mDivider;
    private int mOrientation;
    public itemfenge(Context context, int orientation){
        final TypedArray a= context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }
    public void onDraw(Canvas c, RecyclerView parent) {
        if(mOrientation==VERTICAL_LIST){
            drawVertical(c,parent);
        }else {
            drawHorizontal(c,parent);
        }
        onDraw(c, parent);
    }

    private void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top =  parent.getPaddingTop();
        final int bottom = parent.getHeight()-parent.getPaddingBottom();
        final int childCount = parent.getChildCount();
        for(int i=0;i<childCount;i++){
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight()+params.rightMargin;
            final int right = left+mDivider.getIntrinsicHeight();
            mDivider.setBounds(left,top,right,bottom);
            mDivider.draw(c);
        }
    }

    private void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth()-parent.getPaddingRight();
        final  int childCount = parent.getChildCount();
        for(int i=0; i <childCount; i++){
            final View child =parent.getChildAt(i);
            RecyclerView v= new RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom()+params.bottomMargin;
            final int bottom = top+mDivider.getIntrinsicHeight();
            mDivider.setBounds(left,top,right,bottom);
            mDivider.draw(c);
        }
    }

    @Override
    @Deprecated
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if(mOrientation==VERTICAL_LIST){
            outRect.set(0,0,0,mDivider.getIntrinsicHeight());
        }else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }

    public void setOrientation(int orientation) {
        if(orientation !=HORIZONTAL_LIST&&orientation !=VERTICAL_LIST){
            throw  new IllegalArgumentException("invaslid");
        }
        mOrientation = orientation;
    }
}

8、設(shè)置分割線的顏色(注意布局是shape)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />
    <size android:height="3dp" />

</shape>

結(jié)語(yǔ):

RecyclerView是和很好用的view而且不ListView容易理解。如果我說(shuō)的不對(duì)的地方,希望大家可以給我留言或發(fā)簡(jiǎn)信,我及時(shí)改正——一個(gè)初學(xué)者。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容