Android中可以从xml中读取布局,但是动态添加有时方便很多
首先需要的View
private Context mContext = null;
private TextView view1 = null;
private TextView view2 = null;
private TextView view3 = null;
private RelativeLayout layout = null;
在onCreat中
layout = (RelativeLayout) findViewById(R.id.layout);
mContext = this;
第一种,直接添加,没有布局要求的
private void addView1() {
layout = (RelativeLayout) findViewById(R.id.layout);
view1 = new TextView(mContext);
view1.setLayoutParams(new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view1.setText("TextView1");
view1.setTextColor(0xFF000000);
layout.addView(view1);
}
第二种,规定在第一个的下方并且水平居中
private void addView2() {
view2 = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
view1.setId(1);
params.addRule(RelativeLayout.BELOW, 1);
view2.setLayoutParams(params);
view2.setText("TextView2");
layout.addView(view2);
}
第三种,规定顶端和左边的距离
private void addView3() {
view3 = new TextView(mContext);
MarginLayoutParams mlp = new MarginLayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mlp.setMargins(50, 200, 0, 0);
view3.setLayoutParams(new RelativeLayout.LayoutParams(mlp));
view3.setText("TextView3");
layout.addView(view3);
}
最后可以删除layout内的view
private void removeView2() {
layout.removeViewAt(1);
}
layout内view的放置就和数组一样,第一个的位置是0,第二个是1,以此类推