Hello, Android之UI-XML布局
Android中的用户界面(Activity)可以用两种方式来创建:
1 2 | 通过编写Java代码 通过定义XML布局代码 |
在Hello, Android中,我们采用了第一种方式创建用户界面,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package org.gooss.android.hello; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } } |
下面讲解一下如何使用XML布局来创建Hello, Android应用。
更改HelloAndroid.java文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package org.gooss.android.hello; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } |
其中R.layout.main表示使用/res/layout/main.xml作为XML布局文件,并使用setContentView将其与屏幕显示联系起来。main.xml的内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout> |
@string/hello表示android:text的值引用自/res/values/strings.xml资源文件中名为hello的’string’定义,修改strings.xml文件内容如下:
1 2 3 4 5 | <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello, Android!</string> <string name="app_name">Hello, Android</string> </resources> |
好了,现在可以选择Run > Run History > HelloAndroid菜单或按Ctrl-F11键重新在模拟器中运行Android应用了。
相比较而言,使用XML布局文件定义GUI结构是比较好的方式。这就好像Web开发中的MVC(Model-Viewer-Control)模式一样,将Android UI开发从Android应用逻辑代码中分离了出来。使应用从一个屏幕到另一个屏幕更加简单。而且,在XML中定义一个UI和编写一个HTML文档非常相似并且能够通过树形结构来表达UI。
另外,如同普通Java项目一样,可以为Android项目的设置断点调试并且也支持单步调试:在设置代码中设置断点,并选择Run > Debug As > Android Application菜单进行调试。
Monitor Your Web Site 24/7 - Receive email and SMS alerts anytime your web site goes down.
