0

我在以编程方式创建 relativeLayout 时遇到了一些麻烦。为了更好地理解,我在下面附上了一张图片。加号和减号的东西是按钮,也应该动态创建并添加到布局中。tv4 和 tv5 的值应随着按钮按下而相应增加/减少。

到目前为止我做了什么:

1)创建布局:

RelativeLayout rl = new RelativeLayout(this);
    rl.setId(i);
    rl.setBackgroundResource(R.drawable.bg);
 RelativeLayout.LayoutParams Lparams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        Lparams.addRule(RelativeLayout.BELOW, R.id.RL_default);
        Lparams.setMargins(3, 5, 3, 0);
        rl.setLayoutParams(Lparams);

2)添加电视1:

  Lparams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Lparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    Lparams.setMargins(10, 0, 0, 0);

    TextView txt = new TextView(this);
    txt.setTextColor(Color.parseColor("#FFFFFF"));
    txt.setId(x);
    txt.setTextSize(25);
    txt.setLayoutParams(Lparams);
    txt.setText(name);
            rl.addView(txt);

3)添加电视2:

           Lparams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    Lparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    Lparams.addRule(RelativeLayout.BELOW, txt.getId());
    Lparams.setMargins(10, 0, 0, 0);

    TextView txtS = new TextView(this);
    txtS.setId(y);
    txtS.setText("Test: ");
    txtS.setTextSize(22);

    txtS.setLayoutParams(Lparams);
    txtS.setGravity(Gravity.BOTTOM);
    txtS.setPadding(0, 0, 0, 20);
            rl.addView(txtS);

4)现在我想创建第一个按钮:

           Button btnSminus = new Button(this);
    btnSminus.setId(btn1);
    btnSminus.setText("<");
    btnSminus.setTextSize(20);

    Lparams= new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    Lparams.addRule(RelativeLayout.RIGHT_OF, txtS.getId());


    btnSminus.setLayoutParams(Lparams);
            rl.addView(btnSminus);

问题是,当行 Lparams.addRule(RelativeLayout.RIGHT_OF, txtS.getId()); 时,按钮 View 似乎刚刚从屏幕上消失。被执行。可能是什么原因?

在此处输入图像描述

4

1 回答 1

2

我的猜测是,这是因为您将宽度设置为txtSto match_parent,所以按钮被推离屏幕。您可以通过将其更改为wrap_content.

于 2012-12-25T17:58:02.130 回答