RecycleView的RV的网格排列:

新建一个Activity文件:

package com.example.myfirstapplication.RecyclerView;

import androidx.appcompat.app.AppCompatActivity;

import androidx.recyclerview.widget.GridLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.example.myfirstapplication.R;

public class GridRecyclerActivity extends AppCompatActivity {

    private RecyclerView rv_gird;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_grid_recycler);

        rv_gird = findViewById(R.id.rv_gird);

        rv_gird.setLayoutManager(new GridLayoutManager(GridRecyclerActivity.this,3));

        rv_gird.setAdapter(new GridAdapter(GridRecyclerActivity.this));

    }

}

rv_gird.setLayoutManager(new GridLayoutManager(GridRecyclerActivity.this,3));

这一句就是用来设置网格布局的GridLayoutManager为网格的class里面的要填入GridRecyclerActivity.this要在哪理。

3有多少列。

package com.example.myfirstapplication.RecyclerView;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.ImageView;

import android.widget.TextView;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;

import com.example.myfirstapplication.R;

public class GridAdapter extends RecyclerView.Adapter<GridAdapter.GridAdapterViewHloder> {

    @NonNull

    private Context context;

    private LayoutInflater layoutInflater;

    public GridAdapter(Context context){

        this.context = context;

    }

    public GridAdapter.GridAdapterViewHloder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        return new GridAdapterViewHloder(LayoutInflater.from(context).inflate(R.layout.once_gridview,parent,false));

    }

    @Override

    public void onBindViewHolder(@NonNull GridAdapter.GridAdapterViewHloder holder, int position) {

    }

    class GridAdapterViewHloder extends RecyclerView.ViewHolder{

        private ImageView iv;

        private TextView tv1,tv2;

        public GridAdapterViewHloder(@NonNull View itemView) {

            super(itemView);

            iv = itemView.findViewById(R.id.iv);

            tv1 = itemView.findViewById(R.id.tvname);

            tv2 = itemView.findViewById(R.id.tvcontent);

        }

    }

    @Override

    public int getItemCount() {

        return 30;

    }

}

Adapter:

这里我偷懒一下xml就用之前的。

回到java,setAdapter()。

截屏2020-02-21下午1.24.38.png
最后修改日期:2020年2月21日

作者

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。