以编程方式将视图添加到RelativeLayout内的CardView

问题描述 投票:0回答:1

我需要为RelativeLayout创建CardViews。在CardViews中,还有其他视图,如ImageViews和TextViews。它们被添加,但似乎它们不遵守我添加到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);

我做错了什么?

谢谢。

android android-cardview android-relativelayout
1个回答
0
投票

解决了。问题是,我正在为CardView设置一些不可用的规则,比如CENTER_VERTICAL。所以,我添加了另一个RelativeLayout作为CardView的子,将Views添加到RelativeLayout,将RelativeLayout添加到CardView,现在正确地绘制了Views。

© www.soinside.com 2019 - 2024. All rights reserved.