我需要创建CardViews到RelativeLayout。在CardView内部,还有其他视图,例如ImageView和TextView。它们被添加了,但是似乎它们不遵守我要添加到LayoutParams中的规则。这是我的代码:
CardView infoCardView=new CardView(HotelActivity.this);
infoCardView.setId(2);
RelativeLayout.LayoutParams cardViewParams=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams iconLp=new RelativeLayout.LayoutParams(20,20);
RelativeLayout.LayoutParams textLP=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//imagen is another ImageView that is being drawn ok in the RelativeLayout. Also, the cardView is drawn below the ImageView, which is ok.
cardViewParams.addRule(RelativeLayout.BELOW,imagen.getId());
infoCardView.setLayoutParams(cardViewParams);
iconLp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
iconLp.addRule(RelativeLayout.ALIGN_PARENT_START, RelativeLayout.TRUE);
iconLp.setMarginStart(20);
//Icono del cardView
ImageView icono=new ImageView(HotelActivity.this);
icono.setId(3);
//icono.setLayoutParams(iconLp);
icono.setBackground(getDrawable(android.R.drawable.ic_dialog_info));
infoCardView.addView(icono,iconLp);
//TextView título del CardView
TextView tvInfo=new TextView(HotelActivity.this);
tvInfo.setId(4);
tvInfo.setTextSize(17);
tvInfo.setText(getString(R.string.info));
tvInfo.setTypeface(tvInfo.getTypeface(), Typeface.BOLD);
textLP.addRule(RelativeLayout.END_OF,icono.getId());
textLP.setMarginStart(20);
tvInfo.setTextColor(getColor(R.color.white));
//tvInfo is NOT added to the END of icono, instead is overlapping it.
infoCardView.addView(tvInfo, textLP);
infoCardView.setRadius(9);
infoCardView.setBackgroundColor(Color.parseColor(almacen.getEvento().getBgColor()));
infoCardView.setElevation(9);
rl.addView(infoCardView,cardViewParams);
我做错了什么?
谢谢。
答案 0 :(得分:0)
已解决。问题是,我正在为CardView设置一些不适用于它的规则,例如CENTER_VERTICAL。因此,我添加了另一个RelativeLayout作为CardView的儿子,将视图添加到该RelativeLayout,将该RelativeLayout添加到CardView,现在视图已正确绘制。