package com.paad.helloworld; import android.os.Bundle; public class MyActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
Activity是应用程序中可见的交互组件的基类,它大体上等同于传统桌面应用程序开发中的窗体。上面这个例子,它扩展了Activity,重写了onCreate方法。java
在android中,可视化组件称为视图(View),它们相似于传统桌面应用程序开发中的控件。由于setContentView能够经过扩展一个布局资源来对用户界面进行布局,因此咱们重写了onCreate方法,用它来调用setContentView。android
Android项目的资源存储在项目层次结构的res文件夹中,它包含了layout,values和一系列drawable子文件夹。ADT插件会对这些资源进行解释,并经过R变量来提供对它们的设计时访问。ide
下面的代码显示了定义在由android项目模板建立,并存储在项目的res/layout文件夹中的UI布局:布局
<?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>
使用XML定义UI并对其进行扩展是实现用户界面(UI)的首选方法,由于这样作能够把应用程序逻辑和UI设计分离开来。为了在代码中访问UI元素,能够在XML定义中向它们添加标识符属性。以后就可使用findViewById方法来返回对每一个已命名的项的引用了。下面的XML代码显示了向Hello World模板中的TextView widget中加入的一个ID属性:优化
<TextView android:id="@+id/myTextView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />
下面的代码段则展现了如何在代码中访问UI元素:this
TextView myTextView = (TextView) findViewById(R.id.myTextView);
还有一种方法(虽然被认为是很差的作法),能够直接在代码中建立本身的布局。如例:spa
public void onCreat(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout.LayoutParams lp; lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT); LinearLayout.LayoutParams textViewLP; textViewLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); TextView myTextView = new TextView(this); myTextView.setText(getString(R.string.hello); ll.addView(myTextView,textViewLP); this.addContentView(ll,lp); }
代码中可用的全部属性均可以使用XML布局中的属性来设置。通常来讲,保持可视化设计和应用程序代码的分离也能使代码更简明。考虑到android在数百种具备各类屏幕尺寸的不一样设备上可用,将布局定义为XML资源更便于包含多个针对不一样屏幕进行优化的布局。插件