简单的Android网格示例,使用RecyclerView和GridLayoutManager(像旧的GridView)

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

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

简短的回答

对于那些已经熟悉设置RecyclerView来创建列表的人来说,好消息是制作网格在很大程度上是相同的。当你设置RecyclerView时,你只是使用GridLayoutManager而不是LinearLayoutManager

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

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

完整的示例

下面是一个类似下图的最小示例。

enter image description here

从一个空活动开始。您将执行以下任务来添加RecyclerView网格。您所需要做的就是复制并粘贴每个部分中的代码。稍后,您可以自定义它以满足您的需求。

  • 向gradle添加依赖项
  • 为活动和网格单元格添加xml布局文件
  • 制作RecyclerView适配器
  • 初始化活动中的RecyclerView

更新Gradle依赖项

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

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

你可以将版本号更新为最新的

创建活动布局

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>

创建网格单元格布局

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>

创建适配器

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中可用,并且是一种常见的需求。如果不需要,可以删除此代码。

在Activity中初始化RecyclerView

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

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中处理单元格单击事件。

完成了

就是这样。您现在应该能够运行您的项目,并获得与顶部图像类似的内容。

发生了

圆角

Auto-fitting列

进一步的研究

虽然我确实喜欢并欣赏< em > Suragch < / em >的答案,但我想留下一个提示,因为我发现编码适配器 (MyRecyclerViewAdapter)来定义和公开监听器方法onItemClick并不是最好的方法,因为没有正确使用类封装。所以我的建议是让适配器单独处理监听操作(这是他的目的!),并将这些操作与使用适配器 (MainActivity)的活动分开。这就是我如何设置Adapter类:

MyRecyclerViewAdapter.java

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


private String[] mData = new String[0];
private LayoutInflater mInflater;


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


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


// Binds the data to the textview in each cell
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData[position];
holder.myTextView.setText(animal);
}


// 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 {
public TextView myTextView;


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


@Override
public void onClick(View view) {
onItemClick(view, getAdapterPosition());
}
}


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


// Method that executes your code for the action received
public void onItemClick(View view, int position) {
Log.i("TAG", "You clicked number " + getItem(position).toString() + ", which is at cell position " + position);
}
}

请注意,onItemClick方法现在定义在MyRecyclerViewAdapter中,这是你想要为收到的事件/动作编码任务的地方。

为了完成这个转换,只需要做一个小的改变:活动不再需要实现MyRecyclerViewAdapter.ItemClickListener,因为现在这完全由适配器完成。这将是最后的修改:

MainActivity.java

public class MainActivity extends AppCompatActivity {


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 = (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);
}
}

你应该将你的RecyclerView LayoutManager设置为Gridlayout模式。当你想要设置你的RecyclerView LayoutManager时,只需更改你的代码:

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

RecyclerView初始化中设置

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

这是一种仅使用XML的简单方法

spanCount表示列数

layoutManager使它成为网格或线性(垂直或水平)

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/personListRecyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

在MainActivity中,也就是你分配回收器视图的地方,使用这段代码。

recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
//recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));

如果你想在reyclerview的XML文件中设置网格布局,那么你可以把这两个放在recyclerview XML中。

app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount=numberOfItemsInSignleRow

如果你想从Java代码中设置网格布局,你可以这样写。

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfItemsInSignleRow));
    There are 2 ways to achieve this
    

- In Xml
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/list_amenities"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_8sdp"
android:nestedScrollingEnabled="false"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
app:spanCount="2"
app:layout_constraintEnd_toEndOf="@+id/text_parking_lot_amenities"                       app:layout_constraintStart_toStartOf="@+id/text_parking_lot_amenities"                  app:layout_constraintTop_toBottomOf="@id/text_parking_lot_amenities" />

span count用于网格列
- In activity

 listAmenities.layoutManager = GridLayoutManager(this, TWO)
here TWO indicates number of grid columns