实现一个recycler view实例
时间: 2023-10-12 18:05:04 浏览: 83
下面是一个简单的RecyclerView实例,其中包含一个列表视图,该视图显示一些文本项。
MainActivity.java
```
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
String[] myDataset = {"Item 1", "Item 2", "Item 3"};
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
}
```
MyAdapter.java
```
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text_view);
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mTextView.setText(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
```
activity_main.xml
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
list_item.xml
```
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textAppearance="?android:attr/textAppearanceListItem" />
```
这个RecyclerView实例使用了一个LinearLayoutManager和一个MyAdapter。MyAdapter通过ViewHolder来管理每个列表项的视图。在onCreateViewHolder()方法中,我们使用LayoutInflater将list_item.xml布局文件转换为一个View对象,然后将其传递给ViewHolder。在onBindViewHolder()方法中,我们将mDataset中对应位置的文本设置为ViewHolder中的mTextView中的文本。最后,在MainActivity的onCreate()方法中,我们创建一个LayoutManager和一个Adapter,并将Adapter设置为RecyclerView的适配器。
阅读全文