我正在尝试将ListView重构为RecyclerView,我陷入了这种情况。
在我的ListView适配器中我有这样的东西:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module'; // Added here
我不知道如何将其应用到我的RecyclerView适配器,因为我无法访问onCreateViewHolder 方法中的位置,其中布局应该充气
以下是我的RecyclerView适配器中的方法:
@Override
public int getItemViewType(int position) {
if (mDecommissionMode && position == getCount() - 1)
return 1;
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == 0)
return getNormalView(position, convertView, parent);
else
return getManualDecommissionView(convertView, parent);
}
我有办法应对吗?
答案 0 :(得分:2)
遵循以下三个简单步骤
覆盖getItemViewType(int position)
根据ViewType返回不同的ViewHolders
onCreateViewHolder()
方法
根据onBindViewHolder()
中的itemViewType填充视图
方法(这解决了你面临的位置问题)
这是RecyclerView适配器的小代码片段 您可以查看完整代码以供参考Here
public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
@Override
public int getItemViewType(int position)
{
if(position==0)
return LAYOUT_ONE;
else
return LAYOUT_TWO;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =null;
RecyclerView.ViewHolder viewHolder = null;
if(viewType==LAYOUT_ONE)
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
viewHolder = new ViewHolderOne(view);
}
else
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
viewHolder= new ViewHolderTwo(view);
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder.getItemViewType()== LAYOUT_ONE)
{
}
else {
ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
vaultItemHolder.name.setText(displayText);
vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
.......
}
});
}
}
public class ViewHolderOne extends RecyclerView.ViewHolder {
public TextView name;
public ViewHolderOne(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.displayName);
}
}
public class ViewHolderTwo extends RecyclerView.ViewHolder{
public ViewHolderTwo(View itemView) {
super(itemView);
..... Do something
}
}
}
答案 1 :(得分:1)
在Adapter
课程中添加此
enum VIEW_TYPE {
VIEW1, VIEW2}
然后在适配器中覆盖getItemViewType(int position)
,并根据您在给定VIEW_TYPE.VIEW1.ordinal()
的逻辑返回VIEW_TYPE.VIEW2.ordinal()
或position
。在onCreateView
中,您将获得viewtype值。根据该返回VieHolder
与View