600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > Android 布局学习之——Layout(布局)详解一

Android 布局学习之——Layout(布局)详解一

时间:2019-05-30 20:56:21

相关推荐

Android 布局学习之——Layout(布局)详解一

layout(布局)定义了用户界面的可视化结构(visual structure),如Activity的UI,应用窗口的UI。

有两种方式声明layout:

1.在xml文件中声明UI组件

2.在运行时,实例化布局元素。我们可以以编码的方式创建View或ViewGroup对象,操纵它们的属性。

下面用一个小例子来学习怎样以编码的方式添加layout:

1 import android.app.Activity; 2 import android.graphics.Color; 3 import android.os.Bundle; 4 import android.view.ViewGroup; 5 import android.widget.Button; 6 import android.widget.LinearLayout; 7 import android.widget.TextView; 8 9 public class MainActivity extends Activity {10 11private LinearLayout linearLayout;12private TextView textView;13private Button button;14public static final int VERTICAL = 1;15public static final int MATCH_PARENT = -1;16public static final int WRAP_CONTENT = -2;17@Override18protected void onCreate(Bundle savedInstanceState) {19 super.onCreate(savedInstanceState);20 21 //以编码的方式添加layout22 23 linearLayout = new LinearLayout(this);24 linearLayout.setOrientation(VERTICAL); //设置LinearLayout方向,0是水平,1是垂直。默认是水平。25 //设置布局参数,-1是MATCH_PARENT,-2是WRAP_CONTENT26 //ViewGroup.LayoutParams(int width, int height)27 linearLayout.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,MATCH_PARENT));28 29 textView = new TextView(this);30 textView.setText("ThisIsATextView");31 textView.setBackgroundColor(Color.RED);32 textView.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,WRAP_CONTENT));33 34 button = new Button(this);35 button.setText("ThisIsAButton");36 button.setBackgroundColor(Color.GREEN);37 button.setLayoutParams(new ViewGroup.LayoutParams(MATCH_PARENT,WRAP_CONTENT));38 39 linearLayout.addView(button);40 linearLayout.addView(textView);41 //布局写好后,不要忘记添加到Activity中42 setContentView(linearLayout);434445}46 }

运行效果图:

每个layout文件必须包含一个确定的根元素,这个根元素它必须是View或ViewGroup的对象。

那View类和ViewGroup类的作用是什么呢?

View:

为用户界面组件提供基本的搭建区域。View类是widgets的父类,widgets通常用来创建交互UI组件

如button,TextView等等。View类同时也是ViewGroup类的父类。

ViewGroup:

是layout类的父类,而layout类是保存其他View或ViewGroup的可视化容器(invisible containers),并且能定义它们的布局属性。

通过添加额外的布局对象(layout object)或窗口(widgets)作为子元素来逐渐完善视图层。

下面通过一个layout文件来具体学习以下:

1 <!-- 确定的根元素 LinearLayout是ViewGroup的子类layout的对象 --> 2 <LinearLayout xmlns:android="/apk/res/android" 3xmlns:tools="/tools" 4android:layout_width="match_parent" 5android:layout_height="wrap_content" 6android:orientation="vertical" > 7<!-- 添加子组件来丰富视图层 --> 8<Button 9 android:layout_width="match_parent"10 android:layout_height="wrap_content"11 android:background="#f00"12 android:layout_weight="1"13 android:text="ThisIsAButton" />14<TextView 15 android:layout_width="match_parent"16 android:layout_height="wrap_content"17 android:background="#0f0"18 android:text="ThisIsATextView"19 />20 </LinearLayout>

我们在xml文件中声明好界面的布局方式以后,将xml文件保存在res/layout/下即可。

希望这篇文章对大家的学习有所帮助,如果你喜欢,请推荐一下,谢谢~

如果转载,请在文章开头处注明本博客地址:http:/JohnTsai

欢迎讨论交流,邮箱:JohnTsai.Work@ :)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。