我知道RecyclerView已经取代了旧的ListViewGridView的功能.我正在寻找一个非常基本的例子,它显示了使用RecyclerView的最小网格设置.我不是在寻找冗长的教程式解释,只是一个简单的例子.我设想,模仿旧GridView的最简单网格将包括以下功能:

  • 每行多个单元格
  • 每个单元格中的单个视图
  • 响应点击事件

推荐答案

Short answer

对于那些已经熟悉setting up a RecyclerView to make a list的人来说,好消息是制作网格基本上是一样的.设置RecyclerView时,只需使用GridLayoutManager而不是LinearLayoutManager.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

如果你需要更多的帮助,那么看看下面的例子.

Full example

下面是一个如下图所示的最小示例.

enter image description here

从一个空的活动开始.您将执行以下任务来添加RecyclerView网格.你所需要做的就是复制并粘贴每个部分的代码.稍后,您可以根据自己的需要进行定制.

  • 将依赖项添加到Gradle
  • 为活动和网格单元添加xml布局文件
  • 使ReccyclerView适配器
  • 在您的活动中初始化ReccyclerView

Update Gradle dependencies

确保app gradle.build文件中存在以下依赖项:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

您可以将版本号更新为the most current.

Create activity layout

RecyclerView添加到xml布局中.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

我们的RecyclerView网格中的每个单元格将只有一个TextView.新建布局资源文件.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

RecyclerView需要一个适配器来用数据填充每个单元格中的视图.创建一个新的java文件.

MyRecyclerViewAdapter.java

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

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

笔记

  • 虽然不是严格必要的,但我提供了监听单元格上点击事件的功能.这是在旧的GridView,是一个共同的需要.如果不需要,可以删除此代码.

Initialize RecyclerView in Activity

将以下代码添加到您的主活动中.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

笔记

  • 请注意,该活动实现了我们在适配器中定义的ItemClickListener.这允许我们在onItemClick中处理单元格单击事件.

Finished

就这样.你现在应该能够运行你的项目,并得到类似于顶部图像的东西.

Going on

圆角

自动装配柱

Further study

Android相关问答推荐

如何正确增加LazyStream中的变量

RippleTheme在作曲material 1.7.0中被废弃

如何将Hilt添加到Android Studio中的Kotlin项目中?

Android Kotlin DSL Gradle找不到自定义存储库中的依赖项

fillMaxHeight中的分数在列内不起作用(android jetpack compose)

StateFlow集合AsState没有更新他的值Jetpack Compose导航

LaunchedEffect没有延迟时应用程序崩溃

如何在Jetpack Compose中向SearchBar添加边框

有没有办法迭代类型安全的项目访问器?

Jetpack Compose 中的用户在线指示器

如何在 Jetpack Compose 中对数据类进行 Parcelize

如何在 android compose 中将具有渐变边缘的透明圆圈绘制到阴影覆盖层中?

Android 模拟器 Wifi 连接没有互联网

为什么我要使用 $version 而不是2.7.0?

是否可以在 Kotlin 中为 mutableStateOf() 设置自定义设置器

如何在 TextButton 中分隔文本和图标

如何从 Jetpack Compose 中的 Radio 组中获取价值

Android Studio:如何添加应用程序质量洞察窗口以查看 Android Studio 中的 Crashlytics 数据?

使 Compose LazyColumn 的最后一项填满屏幕的其余部分

react-native android项目未找到错误