我想以编程方式想要这样的东西:
view1 | view2
view3 | view4
----------------
view1 | view2
view3 | view4
----------------
view1 | view2
view3 | view4
---------------
...........
......
which keeps repeating
--------------
我不想使用ListView。
答案 0 :(得分:56)
重要提示:请记住为每个视图设置ID。
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv1 = new TextView(this);
tv1.setId(1);
tv1.setText("textView1");
TextView tv2 = new TextView(this);
params2.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
tv2.setId(2);
tv2.setText("textView2");
TextView tv3 = new TextView(this);
params3.addRule(RelativeLayout.BELOW, tv1.getId());
tv3.setId(3);
tv3.setText("textView3");
TextView tv4 = new TextView(this);
params4.addRule(RelativeLayout.RIGHT_OF, tv3.getId());
params4.addRule(RelativeLayout.ALIGN_BOTTOM, tv3.getId());
tv4.setId(4);
tv4.setText("textView4");
layout.addView(tv1, params1);
layout.addView(tv2, params2);
layout.addView(tv3, params3);
layout.addView(tv4, params4);
答案 1 :(得分:3)
不是像@Askilondz答案中建议的那样使用多个布局参数,您可以使用addRule
和removeRule
,如下所示:
RelativeLayout rl = new RelativeLayout(this.getContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
TextView tv1 = new TextView(this);
tv1.setId(View.generateViewId());
tv1.setText("textView1");
TextView tv2 = new TextView(this);
tv2.setId(View.generateViewId());
tv2.setText("textView2");
lp.addRule(RelativeLayout.BELOW, tv1.getId());
rl.addView(tv2, lp);
lp.removeRule(RelativeLayout.BELOW);
.
.
.
如果您使用的是SDK< 17,你必须创建id's.xml
文件,values -> ids.xml
文件结构如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="tv1" type="id" />
<item name="tv2" type="id" />
</resources>
并在代码中将它们设置为:
tv1.setId(R.id.tv1);
tv2.setId(R.id.tv2);
<强>更新强> 它看起来为同样的LayoutParams添加多个规则不能正常工作,无论如何,我会保留我的答案,以防有人对他有用的东西
答案 2 :(得分:0)
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);