动态创建绝对布局的控件

1
2
3
4
5
6
7
8
void initView() {
TextView tv = new TextView(this);
tv.setText("TextView的内容");
AbsoluteLayout.LayoutParams lp1 = new AbsoluteLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0,100);
absoluteLayout.addView(tv, lp1);
//tv.layout(100, 100, 100, 100);
}

如果原来是 LinearLayout 等布局,则可以嵌套在一个 AbsoluteLayout 中

控件移动

直接 layout 方法就可以,但是有些不能这样移动,于是要用到 LayoutParams:

1
2
3
// 动态创建
AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0,100);
1
2
3
4
LayoutParams layoutParams=tv.getLayoutParams();
layoutParams.height=x;
layoutParams.width=y;
tv.setLayoutParams(layoutParams);

来个复杂一点的

网上找的野教程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 
//设置界面的布局
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
 
//添加一个AbsoluteLayout子布局,并给这个布局添加一个button
AbsoluteLayout abslayout = new AbsoluteLayout (this);
abslayout.setId(11);
Buttonbtn1 = new Button(this);
btn1.setText(”thisis a abslayout button”);
btn1.setId(1);
AbsoluteLayout.LayoutParams lp0 = new AbsoluteLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 100, 0);
abslayout.addView(btn1, lp0 );
//将这个子布局添加到主布局中
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
relativeLayout.addView(abslayout , lp1);
 
//再添加一个子布局
RelativeLayout relativeLayout1 = new RelativeLayout(this);
Button btn2 = newButton(this);
btn2.setText(”thisis a relativeLayout1 button”);
btn2.setId(2);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp2.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
relativeLayout1.addView(btn2 , lp2);
 
//将这个布局添加到主布局中
RelativeLayout.LayoutParams lp11 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp11.addRule(RelativeLayout.BELOW , 11);
relativeLayout.addView(relativeLayout1 , lp11);
}

以上代码执行的操作是:

创建一个RelativeLayout relativeLayou
创建一个AbsoluteLayout abslayout
创建一个Button btn1
btn1添加到abslayout中,然后再把abslayout添加到relativeLayout
然后又创建了一个RelativeLayout relativeLayout1
在创建一个Button btn2
btn2添加到relativeLayout1
最后把relativeLayout1添加到了relativeLayout