Hello World,第一個android程序

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文件夾中,它包含了layoutvalues和一系列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資源更便於包含多個針對不一樣屏幕進行優化的佈局。插件

相關文章
相關標籤/搜索