我尝试使用新的RecyclerView
,但我找不到RecyclerView
的示例,其中不同类型的行/卡片视图会被夸大。
使用ListView
我会覆盖getViewTypeCount
和getItemViewType
,以处理不同类型的行。
我是否应该像#34; old"我应该用LayoutManager
做点什么?我想知道是否有人可以指出我正确的方向。因为我只能找到一种类型的例子。
我想要一张略有不同卡片的清单。或者我应该在scrollView
内使用cardViews
而不是适配器和recyclerView
吗?
答案 0 :(得分:193)
处理类似于iOS的UITableView的行/部分逻辑在Android中并不像在iOS中那么简单,但是,当您使用RecyclerView时 - 您可以做的灵活性要大得多。
最后,它是关于如何确定您在适配器中显示的视图类型的全部内容。一旦你弄明白了,它应该很容易航行(不是真的,但至少你已经有了这样的分类)。
适配器公开了两个你应该覆盖的方法:
getItemViewType(int position)
此方法的默认实现将始终返回0,表示只有一种类型的视图。在您的情况下,情况并非如此,因此您需要找到一种方法来断言哪一行对应于哪种视图类型。与通过行和部分为您管理此功能的iOS不同,此处您只需要依赖一个索引,并且您需要使用开发人员技能来了解某个职位何时与部分标题相关联,以及何时与正常行相关。
createViewHolder(ViewGroup parent, int viewType)
无论如何你需要覆盖这个方法,但通常人们只是忽略viewType参数。根据视图类型,您需要扩充正确的布局资源并相应地创建视图持有者。 RecyclerView将以避免不同视图类型冲突的方式处理不同视图类型的回收。
如果您计划使用默认的LayoutManager,例如LinearLayoutManager
,那么您应该很高兴。如果您正计划制作自己的LayoutManager实现,那么您需要更加努力地工作。您真正需要使用的唯一API是findViewByPosition(int position)
,它在特定位置提供给定视图。由于您可能希望根据此视图的类型进行不同的布局,因此您有以下几种选择:
通常在使用ViewHolder模式时,您可以使用视图持有者设置视图标记。您可以在布局管理器的运行时期间使用它来通过在视图持有者中添加表示此视图的字段来查找视图的类型。
由于您需要一个确定哪个位置与哪个视图类型相关的函数,您可能会以某种方式全局访问此方法(可能是管理数据的单例类?),然后您可以根据位置简单地查询相同的方法。
这是一个代码示例:
// in this sample, I use an object array to simulate the data of the list.
// I assume that if the object is a String, it means I should display a header with a basic title.
// If not, I assume it's a custom model object I created which I will use to bind my normal rows.
private Object[] myData;
public static final int ITEM_TYPE_NORMAL = 0;
public static final int ITEM_TYPE_HEADER = 1;
public class MyAdapter extends Adapter<ViewHolder> {
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == ITEM_TYPE_NORMAL) {
View normalView = LayoutInflater.from(getContext()).inflate(R.layout.my_normal_row, null);
return new MyNormalViewHolder(normalView); // view holder for normal items
} else if (viewType == ITEM_TYPE_HEADER) {
View headerRow = LayoutInflater.from(getContext()).inflate(R.layout.my_header_row, null);
return new MyHeaderViewHolder(headerRow); // view holder for header items
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int itemType = getItemViewType(position);
if (itemType == ITEM_TYPE_NORMAL) {
((MyNormalViewHolder)holder).bindData((MyModel)myData[position]);
} else if (itemType == ITEM_TYPE_HEADER) {
((MyHeaderViewHolder)holder).setHeaderText((String)myData[position]);
}
}
@Override
public int getItemViewType(int position) {
if (myData[position] instanceof String) {
return ITEM_TYPE_HEADER;
} else {
return ITEM_TYPE_NORMAL;
}
}
@Override
public int getItemCount() {
return myData.length;
}
}
以下是这些观看者的样子:
public MyHeaderViewHolder extends ViewHolder {
private TextView headerLabel;
public MyHeaderViewHolder(View view) {
super(view);
headerLabel = (TextView)view.findViewById(R.id.headerLabel);
}
public void setHeaderText(String text) {
headerLabel.setText(text);
}
}
public MyNormalViewHolder extends ViewHolder {
private TextView titleLabel;
private TextView descriptionLabel;
public MyNormalViewHolder(View view) {
super(view);
titleLabel = (TextView)view.findViewById(R.id.titleLabel);
descriptionLabel = (TextView)view.findViewById(R.id.descriptionLabel);
}
public void bindData(MyModel model) {
titleLabel.setText(model.getTitle());
descriptionLabel.setText(model.getDescription());
}
}
当然,此示例假设您已经构建了数据源(myData),以便以这种方式轻松实现适配器。作为一个例子,我将向您展示我如何构建一个显示名称列表的数据源,以及每次名称的第一个字母更改时的标题(假设列表按字母顺序排列) - 类似联系人列表的样子:
// Assume names & descriptions are non-null and have the same length.
// Assume names are alphabetized
private void processDataSource(String[] names, String[] descriptions) {
String nextFirstLetter = "";
String currentFirstLetter;
List<Object> data = new ArrayList<Object>();
for (int i = 0; i < names.length; i++) {
currentFirstLetter = names[i].substring(0, 1); // get the 1st letter of the name
// if the first letter of this name is different from the last one, add a header row
if (!currentFirstLetter.equals(nextFirstLetter)) {
nextFirstLetter = currentFirstLetter;
data.add(nextFirstLetter);
}
data.add(new MyModel(names[i], descriptions[i]));
}
myData = data.toArray();
}
这个例子解决了一个相当具体的问题,但我希望这能让您对如何处理回收器中的不同行类型有一个很好的概述,并允许您在自己的代码中进行必要的调整以满足您的需求。 / p>
答案 1 :(得分:109)
诀窍是创建ViewHolder的子类,然后再投射它们。
public class GroupViewHolder extends RecyclerView.ViewHolder {
TextView mTitle;
TextView mContent;
public GroupViewHolder(View itemView) {
super (itemView);
// init views...
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView mImage;
public ImageViewHolder(View itemView) {
super (itemView);
// init views...
}
}
private static final int TYPE_IMAGE = 1;
private static final int TYPE_GROUP = 2;
然后,在运行时执行以下操作:
@Override
public int getItemViewType(int position) {
// here your custom logic to choose the view type
return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
}
@Override
public void onBindViewHolder (ViewHolder viewHolder, int i) {
switch (viewHolder.getItemViewType()) {
case TYPE_IMAGE:
ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
imageViewHolder.mImage.setImageResource(...);
break;
case TYPE_GROUP:
GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
groupViewHolder.mContent.setText(...)
groupViewHolder.mTitle.setText(...);
break;
}
}
希望它有所帮助。
答案 2 :(得分:31)
根据Gil的回答,我通过重写getItemViewType来解决,如Gil所解释的那样。他的答案很棒,必须标记为正确。在任何情况下,我都会添加代码来达到分数:
在您的回收商适配器中:
@Override
public int getItemViewType(int position) {
int viewType = 0;
// add here your booleans or switch() to set viewType at your needed
// I.E if (position == 0) viewType = 1; etc. etc.
return viewType;
}
@Override
public FileViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == 0) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_layout_for_first_row, parent, false));
}
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_other_rows, parent, false));
}
通过这样做,您可以为任何行设置任何自定义布局!
答案 3 :(得分:14)
这很棘手但是很难,只需复制下面的代码即可完成
package com.yuvi.sample.main;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.yuvi.sample.R;
import java.util.List;
/**
* Created by yubraj on 6/17/15.
*/
public class NavDrawerAdapter extends RecyclerView.Adapter<NavDrawerAdapter.MainViewHolder> {
List<MainOption> mainOptionlist;
Context context;
private static final int TYPE_PROFILE = 1;
private static final int TYPE_OPTION_MENU = 2;
private int selectedPos = 0;
public NavDrawerAdapter(Context context){
this.mainOptionlist = MainOption.getDrawableDataList();
this.context = context;
}
@Override
public int getItemViewType(int position) {
return (position == 0? TYPE_PROFILE : TYPE_OPTION_MENU);
}
@Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case TYPE_PROFILE:
return new ProfileViewHolder(LayoutInflater.from(context).inflate(R.layout.row_profile, parent, false));
case TYPE_OPTION_MENU:
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row_nav_drawer, parent, false));
}
return null;
}
@Override
public void onBindViewHolder(MainViewHolder holder, int position) {
if(holder.getItemViewType() == TYPE_PROFILE){
ProfileViewHolder mholder = (ProfileViewHolder) holder;
setUpProfileView(mholder);
}
else {
MyViewHolder mHolder = (MyViewHolder) holder;
MainOption mo = mainOptionlist.get(position);
mHolder.tv_title.setText(mo.title);
mHolder.iv_icon.setImageResource(mo.icon);
mHolder.itemView.setSelected(selectedPos == position);
}
}
private void setUpProfileView(ProfileViewHolder mholder) {
}
@Override
public int getItemCount() {
return mainOptionlist.size();
}
public class MyViewHolder extends MainViewHolder{
TextView tv_title;
ImageView iv_icon;
public MyViewHolder(View v){
super(v);
this.tv_title = (TextView) v.findViewById(R.id.tv_title);
this.iv_icon = (ImageView) v.findViewById(R.id.iv_icon);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Redraw the old selection and the new
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
});
}
}
public class ProfileViewHolder extends MainViewHolder{
TextView tv_name, login;
ImageView iv_profile;
public ProfileViewHolder(View v){
super(v);
this.tv_name = (TextView) v.findViewById(R.id.tv_profile);
this.iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
this.login = (TextView) v.findViewById(R.id.tv_login);
}
}
public void trace(String tag, String message){
Log.d(tag , message);
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View v) {
super(v);
}
}
}
享受!!!!
答案 4 :(得分:3)
我们可以从下面的方式在单个RecyclerView上实现多个视图: -
Gradle的依赖关系,请添加以下代码: -
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
XML中的RecyclerView
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
活动代码
private RecyclerView mRecyclerView;
private CustomAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] mDataset = {“Data - one ”, “Data - two”,
“Showing data three”, “Showing data four”};
private int mDatasetTypes[] = {DataOne, DataTwo, DataThree}; //view types
...
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
//Adapter is created in the last step
mAdapter = new CustomAdapter(mDataset, mDataSetTypes);
mRecyclerView.setAdapter(mAdapter);
第一个XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="@dimen/hundered”
card_view:cardBackgroundColor=“@color/black“>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding=“@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“Fisrt”
android:textColor=“@color/white“ />
<TextView
android:id="@+id/temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textColor="@color/white"
android:textSize="30sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
第二个XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="100dp"
card_view:cardBackgroundColor="#00bcd4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“DataTwo”
android:textColor="@color/white" />
<TextView
android:id="@+id/score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textColor="#ffffff"
android:textSize="30sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
第三个XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="100dp"
card_view:cardBackgroundColor="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“DataThree” />
<TextView
android:id="@+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textSize="25sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:id="@+id/read_more"
android:background="@color/white"
android:text=“Show More” />
</LinearLayout>
</android.support.v7.widget.CardView>
现在是时候制作适配器,这是在同一个回收站视图上显示不同-2视图的主要内容所以请完整检查此代码: -
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private String[] mDataSet;
private int[] mDataSetTypes;
public static final int dataOne = 0;
public static final int dataTwo = 1;
public static final int dataThree = 2;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
}
}
public class DataOne extends ViewHolder {
TextView temp;
public DataOne(View v) {
super(v);
this.temp = (TextView) v.findViewById(R.id.temp);
}
}
public class DataTwo extends ViewHolder {
TextView score;
public DataTwo(View v) {
super(v);
this.score = (TextView) v.findViewById(R.id.score);
}
}
public class DataThree extends ViewHolder {
TextView headline;
Button read_more;
public DataThree(View v) {
super(v);
this.headline = (TextView) v.findViewById(R.id.headline);
this.read_more = (Button) v.findViewById(R.id.read_more);
}
}
public CustomAdapter(String[] dataSet, int[] dataSetTypes) {
mDataSet = dataSet;
mDataSetTypes = dataSetTypes;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v;
if (viewType == dataOne) {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.weather_card, viewGroup, false);
return new DataOne(v);
} else if (viewType == dataTwo) {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.news_card, viewGroup, false);
return new DataThree(v);
} else {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.score_card, viewGroup, false);
return new DataTwo(v);
}
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
if (viewHolder.getItemViewType() == dataOne) {
DataOne holder = (DataOne) viewHolder;
holder.temp.setText(mDataSet[position]);
}
else if (viewHolder.getItemViewType() == dataTwo) {
DataThree holder = (DataTwo) viewHolder;
holder.headline.setText(mDataSet[position]);
}
else {
DataTwo holder = (DataTwo) viewHolder;
holder.score.setText(mDataSet[position]);
}
}
@Override
public int getItemCount() {
return mDataSet.length;
}
@Override
public int getItemViewType(int position) {
return mDataSetTypes[position];
}
}
您还可以查看此link以获取更多信息。
答案 5 :(得分:2)
您必须在RecyclerView.Adapter
中实施getItemViewType()
方法。默认情况下,此方法的onCreateViewHolder(ViewGroup parent, int viewType)
实现viewType
会返回0
。首先,您需要查看位置上的项目类型以便查看回收,并且您必须覆盖getItemViewType()
方法,在该方法中您可以传递viewType
,这将返回您的项目位置。代码示例如下:
@Override
public MyViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
switch (listViewItemType) {
case 0: return new ViewHolder0(...);
case 2: return new ViewHolder2(...);
}
}
@Override
public int getItemViewType(int position) {
return position;
}
// and in the similar way you can set data according
// to view holder position by passing position in getItemViewType
@Override
public void onBindViewHolder(MyViewholder viewholder, int position) {
int listViewItemType = getItemViewType(position);
// ...
}
答案 6 :(得分:1)
您只需返回ItemViewType并使用它即可。见下面的代码:
@Override
public int getItemViewType(int position) {
Message item = messageList.get(position);
// return my message layout
if(item.getUsername() == Message.userEnum.I)
return R.layout.item_message_me;
else
return R.layout.item_message; // return other message layout
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
return new ViewHolder(view);
}
答案 7 :(得分:1)
您可以使用该库:https://github.com/vivchar/RendererRecyclerViewAdapter
mRecyclerViewAdapter = new RendererRecyclerViewAdapter(); /* included from library */
mRecyclerViewAdapter.registerRenderer(new SomeViewRenderer(SomeModel.TYPE, this));
mRecyclerViewAdapter.registerRenderer(...); /* you can use several types of cells */
对于每个项目,您应该实现ViewRenderer,ViewHolder,SomeModel:
ViewHolder - 它是回收者视图的简单视图持有者。
SomeModel - 它是具有ItemModel
接口
public class SomeViewRenderer extends ViewRenderer<SomeModel, SomeViewHolder> {
public SomeViewRenderer(final int type, final Context context) {
super(type, context);
}
@Override
public void bindView(@NonNull final SomeModel model, @NonNull final SomeViewHolder holder) {
holder.mTitle.setText(model.getTitle());
}
@NonNull
@Override
public SomeViewHolder createViewHolder(@Nullable final ViewGroup parent) {
return new SomeViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.some_item, parent, false));
}
}
有关详细信息,您可以查看文档。
答案 8 :(得分:1)
我认为,创建此类回收站的起点 是这种方法的知识。由于此方法是可选的 重写,因此默认情况下在RecylerView类中不可见 这又使许多开发人员(包括我在内)想知道在哪里 开始。一旦知道该方法存在,就创建这样的方法 RecyclerView简直是步履蹒跚。
您可以使用任意数量的不同Views(ViewHolders)创建一个RecyclerView
。但是为了获得更好的可读性,让我们以一个带有两个RecyclerView
的{{1}}为例。
记住这些 3个简单步骤,您会很高兴。
Viewholders
getItemViewType(int position)
返回不同的ViewHolders
onCreateViewHolder()方法基于ViewType
方法中的itemViewType填充视图
这是您的代码段
onBindViewHolder()
这里是project,其中我实现了带有多个ViewHolders的RecyclerView。
答案 9 :(得分:0)
您可以使用此库:
https://github.com/kmfish/MultiTypeListViewAdapter(由我写)
安装适配器:
adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);
对于每个订单项:
public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {
TextView tvName;
TextView tvDesc;
@Override
public int onGetLayoutRes() {
return R.layout.list_item1;
}
@Override
public void bindViews(View convertView) {
Log.d("item1", "bindViews:" + convertView);
tvName = (TextView) convertView.findViewById(R.id.text_name);
tvDesc = (TextView) convertView.findViewById(R.id.text_desc);
tvName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onNameClick(getData());
}
}
});
tvDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onDescClick(getData());
}
}
});
}
@Override
public void updateView(TextModel model, int pos) {
if (null != model) {
Log.d("item1", "updateView model:" + model + "pos:" + pos);
tvName.setText(model.getName());
tvDesc.setText(model.getDesc());
}
}
public interface OnItem1ClickListener {
void onNameClick(TextModel model);
void onDescClick(TextModel model);
}
}