布局学习3之代码布局1
在android开发中,对于一些简单的界面,用布局学习1和布局学习2的方法都可以对付,但是对于一些复杂的界面系统。界面是由很多view组成的,显示的view几层叠加的,最上面一层是由不同的view组成的。在这里举一个例子增强现实(AR)系统。AR界面通常是由一系列的view组成的,比如最里面一层一般是camera view在这一层上面有时绘画层(view)。绘画层又有其他view比如button, seekbar等。对于普通的用xml布局方法来说,就存在着缺陷和不足。针对这些问题,可以用代码布局来解决。对于一些初学者来说就难以理解一些复杂系统的界面代码布局设计,为了方便大家以后理解增强现实系统,我在这里先介绍一些基本的代码布局。
先来看例子:
xml布局通过下面代码实现
publicclassCodeLayoutActivityextends Activity{
/** Called when the activity isfirst created. */
@Override
publicvoid onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
而通过代码布局实现同样的效果。代码如下:
publicclassCodeLayoutActivityextends Activity{
/** Called when the activity isfirst created. */
@Override
publicvoid onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l1 =new LinearLayout(this);
l1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
l1.setOrientation(LinearLayout.VERTICAL);
Button b1 =new Button(this);
b1.setText("Ok");
LinearLayout.LayoutParams ll1 =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
l1.addView(b1, ll1);
setContentView(l1);
}
}运行后的界面
下面对其中的代码进行详解:
LinearLayout l1 =new LinearLayout(this);
相对布局实例化;
l1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
相对布局的具体长度和宽度;这个语句相当于xml布局中:android:layout_width="fill_parent"
android:layout_height="fill_parent"
l1.setOrientation(LinearLayout.VERTICAL);
排列方向位垂直。这个相当于xml布局中android:orientation="vertical"
Button b1 =new Button(this);
b1.setText("Ok");,
实例化一个Button,并设置文本位OK.相当于android:text=”OK”;
LinearLayout.LayoutParamsll1 =newLinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
这里要重点理解一下
LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT
表示Button的大小相当于xml布局中button属性
android:layout_width="fill_parent"
android:layout_height="wrapcontent"
其中LayoutParams表示告诉父view button放在什么view什么位置,举一个简单的例子,LayoutParam表示在象棋棋盘中几行几列的作用,是一个确定位置的属性方法。
在这里我们可以设置:ll1.topMargin= 50;
ll1.leftMargin = 100;
代码增加了这个,运行结果
大家可以看到button位置发生了变化。
setContentView(l1);表示现实的内容(view).
l1.addView(b1, ll1);表示在在相对布局什么位置(ll1)增加b1。
源代码请下载:
http://download.csdn.net/detail/tianke0711/4665988
待续,请耐心等待!