我在以编程方式创建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)添加tv1:
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)添加tv2:
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似乎刚从屏幕上消失;被执行。可能是什么原因?
答案 0 :(得分:2)
我的猜测是因为你将txtS
的宽度设置为match_parent
,所以按钮会被推离屏幕。您可以通过将其更改为wrap_content
来解决此问题。