RelativeLayout addRule不起作用

时间:2016-02-16 20:58:59

标签: android relativelayout

伙计我有一个cardview,我想用规则添加2个按钮,但是 addRule()方法不起作用。在图片中,图A正在出现,但我想制作图B,我的意思是,我希望按钮设置为align_parent_right和align_parent_bottom,第二个按钮与第一个按钮相邻。当我运行它时,图A出现。有什么建议吗?

enter image description here

RelativeLayout.LayoutParams rl= (RelativeLayout.LayoutParams) iView.getLayoutParams();        
RelativeLayout.LayoutParams lparams = new RelativeLayout.LayoutParams(width/4,height/5);
RelativeLayout.LayoutParams lparams2 = new RelativeLayout.LayoutParams(width/4,height/5);

removeButton=new Button(mContext);
modifyButton=new Button(mContext);

lparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
lparams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

cardView.setLayoutParams(rl);

cardView.addView(removeButton,lparams);
cardView.addView(modifyButton,lparams2);

1 个答案:

答案 0 :(得分:0)

试试这个: -

 RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.mainLayout);

        CardView cardView = new CardView(this);
        ViewGroup.LayoutParams cardParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        cardView.setLayoutParams(cardParams);
        mainLayout.addView(cardView);

        RelativeLayout relativeLayout = new RelativeLayout(this);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        relativeLayout.setLayoutParams(layoutParams);
        cardView.addView(relativeLayout);

        LinearLayout linearLayout = new LinearLayout(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setGravity(Gravity.RIGHT);
        relativeLayout.addView(linearLayout);

        Button removeButton = new Button(this);
        Button modifyButton = new Button(this);

        removeButton.setText("Remove");
        modifyButton.setText("Modify");

        linearLayout.addView(removeButton);
        linearLayout.addView(modifyButton);