我知道RecyclerView
已取代旧ListView
和GridView
的功能。我正在寻找一个非常基本的示例,它使用RecyclerView
显示最小的网格设置。我不是在寻找长篇教程风格的解释,只是一个最小的例子。我想模仿旧GridView的最简单的网格将包含以下功能:
答案 0 :(得分:392)
对于那些已经熟悉setting up a RecyclerView
to make a list的人来说,好消息是制作网格大致相同。设置GridLayoutManager
时,只需使用LinearLayoutManager
代替RecyclerView
。
recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
如果您需要更多帮助,请查看以下示例。
以下是一个最小示例,如下图所示。
从空活动开始。您将执行以下任务以添加RecyclerView
网格。您需要做的就是复制并粘贴每个部分中的代码。稍后您可以根据自己的需要进行自定义。
确保您的应用gradle.build
文件中包含以下依赖项:
compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'
您可以将版本号更新为the most current。
将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
中可用,并且是常见的需求。如果您不需要,可以删除此代码。将以下代码添加到您的主要活动中。
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
。那就是它。您现在应该可以运行项目并获得与顶部图像类似的内容。
圆角
自动拟合列
答案 1 :(得分:6)
虽然我喜欢并感谢Suragch's answer,但我想留言,因为我发现编码 Adapter (MyRecyclerViewAdapter
)来定义和公开Listener方法由于没有正确使用类封装,onItemClick
不是最好的方法。所以我的建议是让 Adapter 单独处理Listening操作(这是他的目的!)并将它们与使用 Adapter 的Activity分开({{ 1}})。这就是我设置Adapter类的方法:
MyRecyclerViewAdapter.java
MainActivity
请注意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
方法,您可以在此处为所接收的事件/操作编写任务代码。
要完成此转换,只需做一些小改动: Activity 不再需要实现MyRecyclerViewAdapter
,因为现在完全由适配器。这将是最后的修改:
MainActivity.java
MyRecyclerViewAdapter.ItemClickListener
答案 2 :(得分:1)
您必须将recyclerview layoutmanager设置为Gridlayout模式,为此,只需在要设置RecyclerView LayoutManager时更改代码即可:
注意:将所需的列数替换为### HELP ###
superview.clipsToBounds = false
答案 3 :(得分:1)
设置RecyclerView
初始化
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
答案 4 :(得分:0)
在build.gradle中添加RecyclerView依赖项
compile 'com.android.support:recyclerview-v7:25.1.1'
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--TODO(2): RecyclerView inside FrameLayout-->
<android.support.v7.widget.RecyclerView
android:id="@+id/rvStudents"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
>
</android.support.v7.widget.RecyclerView>
<!--TODO(3): Create one layout resource with item_student.xml name-->
</FrameLayout>
item_student.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#d2d2d2"
android:id="@+id/llItemStudents"
android:layout_margin="8dp"
>
<!--TODO(4): Remember to change the height of LinearLayout to wrap_content and also add its ID-->
<!--TODO(5): Add two TextView which will display student name and mobile number respectively-->
<TextView
android:id="@+id/tvStudentName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:padding="8dp"
android:textSize="25sp"
android:textStyle="bold"
android:textColor="@color/colorPrimary"
/>
<TextView
android:id="@+id/tvMobileNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:padding="8dp"
android:textSize="22sp"
android:textStyle="bold"
android:textColor="@color/colorAccent"
/>
</LinearLayout>
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Layout;
import java.util.ArrayList;
/*
* Demo Code of Recycler View
* Created on: 19th Feb, 2017
* Author Name: Rajat Talesra
* Company Name: WiseL
* This code is for Android Monk Campus Program.
*/
/*
* Recycler View is mainly used to show dynamic list of data.
* Many applications including Whatsapp, Facebook, Gmail, etc. used RecyclerView
*
* RecyclerView mainly uses two main components LayoutManager and Adapter
*
* LayoutManger: Helps to arrange data in LinearLayout or GridLayout
*
* Adapter: Helps to connect our recycler view with the custom layout and display data on screen
*
* In this demo we will display students list with their names and mobile numbers.
*/
public class MainActivity extends AppCompatActivity {
//TODO(6): Create arrayList for student names and ids.
ArrayList<String> namesArrayList = new ArrayList<>();
ArrayList<String> mobileArrayList = new ArrayList<>();
//TODO(7): Declare below mentioned components.
RecyclerView rvStudentsList;
RecyclerView.LayoutManager rvLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//TODO(10): Add data to arrayList
namesArrayList.add("Student 1");
namesArrayList.add("Student 2");
namesArrayList.add("Student 3");
namesArrayList.add("Student 4");
namesArrayList.add("Student 5");
namesArrayList.add("Student 6");
namesArrayList.add("Student 7");
namesArrayList.add("Student 8");
namesArrayList.add("Student 9");
namesArrayList.add("Student 10");
mobileArrayList.add("8766986401");
mobileArrayList.add("8766986402");
mobileArrayList.add("8766986403");
mobileArrayList.add("8766986404");
mobileArrayList.add("8766986405");
mobileArrayList.add("8766986406");
mobileArrayList.add("8766986407");
mobileArrayList.add("8766986408");
mobileArrayList.add("8766986409");
mobileArrayList.add("8766986410");
//TODO(9): Connect UI elements with java objects.
rvStudentsList = (RecyclerView) findViewById(R.id.rvStudents);
//User this to display items vertically
//rvLayoutManager = new LinearLayoutManager(this);
//User this to display items in Grid Layout with 2 columns
rvLayoutManager = new GridLayoutManager(this,2);
//TODO(10): Attach layoutManager to recycler view
rvStudentsList.setLayoutManager(rvLayoutManager);
/*
* Now we need to create one adapter, so that we can display data row wise
* For this we will create our custom adapter, i.e. StudentAdapter.java
*/
//TODO(11): Create new java class StudentAdapter.java
//TODO(16): Pass data to our custom adapter
StudentAdapter studentAdapter = new StudentAdapter(this,namesArrayList,mobileArrayList);
//TODO(17): Attach studentAdapter to recycler view
rvStudentsList.setAdapter(studentAdapter);
//TODO(18): Run your app.
}
}
StudentAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
//TODO(12): StudentAdapter extends RecyclerView Adapter with ViewHolder class
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {
//TODO(13): Create two empty arrayList and one context variable;
Context mainActivityContext;
ArrayList<String> namesArrayList = new ArrayList<>();
ArrayList<String> mobileArrayList = new ArrayList<>();
//TODO(14): Create one constructor with three parameters which will passed from MainActivity class
public StudentAdapter(Context mainActivityContext, ArrayList<String> namesArrayList, ArrayList<String> mobileArrayList) {
this.mainActivityContext = mainActivityContext;
this.namesArrayList = namesArrayList;
this.mobileArrayList = mobileArrayList;
}
//TODO(15): Complete each method as mentioned below
@Override
public StudentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Used to connect our custom UI to our recycler view
View v = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_student, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(StudentAdapter.ViewHolder holder, int position) {
//Used to set data in each row of recycler view
String currentName = namesArrayList.get(position);
String currentMobileNumber = mobileArrayList.get(position);
holder.tvName.setText(currentName);
holder.tvMobileNumber.setText(currentMobileNumber);
}
@Override
public int getItemCount() {
//Returns total number of rows inside recycler view
return namesArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
//Used to work with the elements of our custom UI.
LinearLayout llItemStudents;
TextView tvName;
TextView tvMobileNumber;
public ViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvStudentName);
tvMobileNumber = (TextView) itemView.findViewById(R.id.tvMobileNumber);
llItemStudents = (LinearLayout) itemView.findViewById(R.id.llItemStudents);
llItemStudents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mainActivityContext,
"You clicked item number: "+ getAdapterPosition(),
Toast.LENGTH_SHORT).show();
}
});
}
}
}
也请访问official doc
答案 5 :(得分:0)
这是仅来自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" />