Android Official Documentation provided a tutorial for creating a RecyclerView in Activity. However, it is a bit different when trying to create a RecyclerView in Fragment instead.
Android官方文档提供了在Activity中创建RecyclerView的教程 。 但是,尝试在Fragment中创建RecyclerView时却有些不同。
Open Android Studio, Create new project -> select Basic Activity -> Finish Application creation. Once you run the app on emulator, you will see a single activity application with a button which allows you to switch between two fragments.
打开Android Studio,创建新项目->选择基本活动 ->完成应用程序的创建。 在模拟器上运行该应用程序后,您将看到一个带有按钮的单个活动应用程序,该按钮可让您在两个片段之间进行切换。
We are going to create a RecyclerView resource in SecondFragment. Go to /res/layout/fragment_second.xml, add the following lines to create RecyclerView:
我们将在SecondFragment中创建一个RecyclerView资源。 转到/res/layout/fragment_second.xml,添加以下行以创建RecyclerView:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="409dp" android:layout_height="460dp" android:layout_marginStart="1dp" android:layout_marginTop="1dp" android:layout_marginEnd="1dp" android:layout_marginBottom="1dp" android:visibility="visible" app:layout_constraintBottom_toTopOf="@+id/button_second" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />Alternatively, we can also use Palette in Android Studio to create RecyclerView:
另外,我们也可以在Android Studio中使用Palette创建RecyclerView:
Drag RecyclerView from Palette to Layout in fragment_second.xml (using Design view). 将RecyclerView从Palette拖动到fragment_second.xml中的Layout(使用“设计”视图)。 Define RecyclerView id as `recyclerview`. 将RecyclerView ID定义为`recyclerview`。Since this is created under ConstraintLayout, define Constraint Widget in 4 directions under Layout.
由于这是在ConstraintLayout下创建的,因此请在Layout下的4个方向上定义Constraint Widget 。
After creating RecyclerView, we need to define resource for each item (TextView) in RecyclerView. Create a new file under /res/layout/: frame_textview.xml:
创建RecyclerView之后,我们需要为RecyclerView中的每个项目(TextView)定义资源。 在/ res / layout /下创建一个新文件: frame_textview.xml :
Copy the following lines to this new file.
将以下行复制到此新文件。
<?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:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="8dp"> <TextView android:id="@+id/randomText" android:layout_width="wrap_content" android:layout_height="wrap_content" tools:text="This is some temp text" /></FrameLayout>Alternatively, you can also use Palette to create TextView
或者,您也可以使用Palette创建TextView
Drag TextView from Palette to Layout in frame_textview.xml (using Design view). 将TextView从Palette拖动到frame_textview.xml中的Layout(使用“设计”视图)。 Define TextView id as `randomText` 将TextView ID定义为`randomText`Step 4: Add RecyclerView in Fragment
步骤4:在Fragment中添加RecyclerView
Under recyclerview/SecondFragment.java, add the following lines to inject recyclerView to fragment. Note that ReyclerView needs to be retrieved by using the view.findViewById() instead findViewById() directly. view can retrieved from inflater.inflate().
在recyclerview / SecondFragment.java下 ,添加以下行以将recyclerView注入片段。 请注意,需要使用view.findViewById()而不是直接使用findViewById()来检索ReyclerView 。 可以从inflater.inflate()中检索视图 。
public class SecondFragment extends Fragment {// Add RecyclerView member private RecyclerView recyclerView; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_second, container, false);// Add the following lines to create RecyclerViewrecyclerView = view.findViewById(R.id.recyclerview); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext())); recyclerView.setAdapter(new RandomNumListAdapter(1234)); return view; }Under recyclerview/, create RecyclerViewHolder.java, add the following lines to define how to create a ViewHolder. One ViewHolder contains necessary UI information about one item in RecyclerView. In this example, itemView is the FrameLayout component from step #3. We need to retrieve and store TextView randomText from FrameLayout.
在recyclerview /下 ,创建RecyclerViewHolder.java ,添加以下行以定义如何创建ViewHolder。 一个ViewHolder包含有关RecyclerView中一项的必要UI信息。 在此示例中,itemView是步骤#3中的FrameLayout组件。 我们需要从FrameLayout检索和存储TextView randomText 。
package com.google.firebase.recyclerview;import android.view.View;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;public class RecyclerViewHolder extends RecyclerView.ViewHolder { private TextView view; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); view = itemView.findViewById(R.id.randomText); } public TextView getView(){ return view; }}Under recyclerview/, create RandomNumListAdapter.java, add the following lines to define how to adapter data to RecyclerView.
在recyclerview /下 ,创建RandomNumListAdapter.java ,添加以下行以定义如何将数据适配器到RecyclerView。
Here we want to show a list of Random numbers in RecyclerView, therefore we take a randomness seed as parameter in constructor.
这里我们想在RecyclerView中显示一个随机数列表,因此我们将随机性种子作为构造函数中的参数。
In getItemViewType(), we will provide the layout file which contains the TextView for list item. In this example, this is frame_textview from Step #3.
在getItemViewType()中 ,我们将提供包含列表项的TextView的布局文件。 在此示例中,这是步骤#3中的 frame_textview 。
In onCreateViewHolder(), we take the viewType which is the returned by getItemViewType(). After inflating FrameLayout to get View object, we then can use RecyclerViewHolder created by Step #5 for return value.
在onCreateViewHolder()中 ,我们采用viewType,它是getItemViewType()返回的。 膨胀FrameLayout以获取View对象后,我们可以使用由步骤5创建的RecyclerViewHolder作为返回值。
In onBindViewHolder(), we will bind the RecyclerViewHolder to RecyclerView. In this example, we will generate a random number at runtime for this view item. Note that random number will be generated every time a ViewHolder is bind to RecyclerView, so we can implicitly know that if an item is unbind and bind again at the same position.
在onBindViewHolder()中 ,我们将RecyclerViewHolder绑定到RecyclerView。 在此示例中,我们将在运行时为此视图项生成一个随机数。 请注意,每次将ViewHolder绑定到RecyclerView时,都会生成随机数,因此我们可以隐式知道是否取消绑定项并在同一位置再次绑定。
package com.google.firebase.recyclerview;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView;import java.util.Random;public class RandomNumListAdapter extends RecyclerView.Adapter<RecyclerViewHolder> { private Random random; public RandomNumListAdapter(int seed) { this.random = new Random(seed); } @Override public int getItemViewType(final int position) { return R.layout.frame_textview; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { holder.getView().setText(String.valueOf(random.nextInt())); } @Override public int getItemCount() { return 100; }}Now all the code changes are done, run the app again and click NEXT button on emulator. If you see a list of random numbers as below, congratulations! You have created a RecyclerView in this fragment!
现在,所有代码更改均已完成,再次运行该应用程序,然后单击模拟器上的NEXT按钮。 如果您看到如下随机数列表,那么恭喜! 您已经在此片段中创建了RecyclerView!
If you scroll down the RecyclerView, you will see more random numbers. And if you scroll up, you will find that the numbers are different than the number at the same position before. That is because the view item out of screen will be automatically recycled and bind as another view item currently on the screen. Everytime an item is bind to RecyclerView, this app will generate a new random number and set to TextView.
如果向下滚动RecyclerView,将看到更多随机数。 如果向上滚动,您会发现这些数字与之前相同位置的数字不同。 这是因为屏幕外的视图项将被自动回收并绑定为当前在屏幕上的另一个视图项。 每次将项目绑定到RecyclerView时,此应用都会生成一个新的随机数并将其设置为TextView。
翻译自: https://medium.com/swlh/create-recyclerview-in-android-fragment-c0f0b151125f