我正在尝试创建一个模仿下面图片的布局。
我需要在列表中调用两个xml文件。它们的属性和列表中的行数是动态的,因此在运行时填充。他们的高度是一样的。然而,它们的宽度必须以1:1:1.3的比例分布在整个屏幕上。
我首先尝试使用gridview,然后我尝试使用gridlayoutmanager进行recyclerview。我可以在适配器的onBindViewHolder()中静态设置宽度。但它对于不同的屏幕来说是不同的,也会影响我使用RecyclerView.ItemDecoration设置的项目之间的间距。有没有办法动态设置项目的宽度w.r行中的其他项目?
以下是我的代码的一部分:
在活动的onCreate()中:
recyclerViewLayoutManager = new GridLayoutManager(context,3);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen._3sdp);
recyclerView.addItemDecoration(new StoreSpaces(spacingInPixels));
recyclerView.setLayoutManager(recyclerViewLayoutManager);
recyclerView.setAdapter(new StoreRecycleAdapter(context,backgroundTheme, categoryNames));
适配器类:
public class StoreRecycleAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
int[] contentBg ;
final int CATEGORY =0, SUBCATEGORY=1;
String[] catNames;
StoreRecycleAdapter (Context context, int[] contentBg, String[] catNames){
this.contentBg =contentBg;
this.context =context;
this.catNames =catNames
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case CATEGORY:
View v1 = inflater.inflate(R.layout.category,parent, false);
viewHolder = new ViewHolder1(v1);
break;
case SUBCATEGORY:
View v2 = inflater.inflate(R.layout.subcategory, parent, false);
viewHolder = new ViewHolder1(v2);
break;
default:
View v3 = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
viewHolder = new ViewHolder1(v3);
break;
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case CATEGORY:
break;
case SUBCATEGORY:
/* ViewGroup.LayoutParams params2 = holder.itemView.getLayoutParams();
params2.width =270;
holder.itemView.setLayoutParams(params2);*/
ViewHolder1 vh1 = (ViewHolder1) holder;
vh1.gridText.setText(catNames[position]);
vh1.gridLL.setBackgroundResource(contentBg[position]);
break;
default:
break;
}
}
@Override
public int getItemViewType(int position) {
if ((position-2)%3==0 ) {
return CATEGORY;
} else
return SUBCATEGORY;
}
@Override
public int getItemCount() {
return catNames.length ;
}
public class ViewHolder1 extends RecyclerView.ViewHolder{
RelativeLayout gridLL;
TextView gridText;
public ViewHolder1(View v){
super(v);
gridLL = (RelativeLayout) v.findViewById(R.id.gridLayout);
gridText = (TextView) v.findViewById(R.id.nameTxt);
}
}
}