Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 介面開發入門:七個常用系統控件的完整用法整理

編輯:關於 Android 開發

寫 Android 介面時,真正天天用到的其實就是那幾個基礎控件。這篇整理我用一個 Demo 專案把常見系統控件的用法全部走過一遍,包含 XML 靜態宣告與 Java 動態建立兩種寫法——順便也能感受到 Android 介面開發的靈活程度:同一個效果,兩種路徑都能到達。

1. 文字標籤 TextView

TextView 是最基礎的顯示元件。下面先用 XML 宣告一個,再用程式碼動態 new 一個加入版面,兩種做法的屬性幾乎一一對應。

程式碼動態建立的部分:

public class TextViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.textview);

        LinearLayout ll = (LinearLayout) findViewById(R.id.textviewll);

        TextView textView = new TextView(this);
        textView.setText("從程式碼中加入一個 TextView");                 // 顯示文字
        textView.setTextColor(Color.WHITE);                             // 文字顏色
        textView.setTextSize(18);                                       // 字級大小
        textView.setBackgroundColor(Color.BLUE);                        // 背景顏色
        textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); // 對齊方式

        ll.addView(textView);   // 把這個 View 加入版面

        super.onCreate(savedInstanceState);
    }
}

對應的 XML 寫法:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/textviewll"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/textView0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="@string/textView"
        android:gravity="center_vertical|center_horizontal" />
</LinearLayout>

實務建議:靜態的、不會變動的文字用 XML 宣告,視覺參數集中在版面檔裡更好維護;需要依資料動態決定內容或樣式時,才用程式碼建立。

2. 網頁元件 WebView

WebView 可以在應用內嵌一段 HTML 內容,甚至直接載入網頁。這裡用 loadDataWithBaseURL 塞入一段含有連結的 HTML 字串,並明確指定 MIME 類型與編碼,避免中文或特殊字元出現亂碼。

public class WebViewActivity extends Activity {

    WebView webView = null;
    static final String MIME_TYPE = "text/html";
    static final String ENCODING  = "utf-8";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.webview);

        webView = (WebView) findViewById(R.id.webview);
        webView.loadDataWithBaseURL(null,
                "<a href='https://example.com'>歡迎訪問我的部落格</a>",
                MIME_TYPE, ENCODING, null);

        super.onCreate(savedInstanceState);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/textviewll"
    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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="網頁框 WebView 測試"
        android:gravity="center_vertical|center_horizontal" />

    <WebView
        android:id="@+id/webview"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" />
</LinearLayout>

提醒:若要載入網路網頁而非本地字串,記得加上 android.permission.INTERNET 權限。

3. 選單 Menu

Menu 在 Android 裡相當有特色:點一下浮現、再點一下消失。只要覆寫 onCreateOptionsMenu 加入項目,再覆寫 onOptionsItemSelected 處理點擊即可。Menu 其實還能做半透明背景、自訂圖示等變化,這裡先示範最基礎的用法。

public class MenuActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.menuview);
        super.onCreate(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, Menu.NONE, "菜單1").setIcon(R.drawable.icon);
        menu.add(0, 1, Menu.NONE, "菜單2").setIcon(R.drawable.icon);
        menu.add(0, 2, Menu.NONE, "菜單3").setIcon(R.drawable.icon);
        menu.add(0, 3, Menu.NONE, "菜單4").setIcon(R.drawable.icon);
        menu.add(0, 4, Menu.NONE, "菜單5").setIcon(R.drawable.icon);
        menu.add(0, 5, Menu.NONE, "菜單6").setIcon(R.drawable.icon);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Dialog(item.getItemId());
        return super.onOptionsItemSelected(item);
    }

    private void Dialog(int message) {
        new AlertDialog.Builder(this)
                .setMessage("您單擊第【" + message + "】項 Menu 選單。")
                .show();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="Menu 選單測試"
        android:gravity="center_vertical|center_horizontal" />
</LinearLayout>

menu.add() 的第一個參數是群組 ID、第二個是項目 ID、第三個是排序,最後才是文字。同一群組內的項目會被視為相關的一組,之後要批次處理時很方便。

4. 按鈕 Button 與 ImageButton

這裡示範兩種按鈕:純文字的一般 Button,以及帶圖片的 ImageButton。兩者都透過 setOnClickListener 掛上點擊事件,用 Toast 給出回饋。

public class ButtonActivity extends Activity {

    Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.buttonview);
        mContext = this;

        // 一般文字按鈕
        Button button0 = (Button) findViewById(R.id.buttonview0);
        button0.setTextColor(Color.BLUE);    // 文字顏色
        button0.setTextSize(30);             // 文字大小

        button0.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(ButtonActivity.this,
                        "您點擊了「這是一個按鈕」", Toast.LENGTH_LONG).show();
            }
        });

        // 帶圖片的按鈕
        ImageButton button1 = (ImageButton) findViewById(R.id.buttonview1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Toast.makeText(ButtonActivity.this,
                        "您點擊了一個帶圖片的按鈕", Toast.LENGTH_LONG).show();
            }
        });

        super.onCreate(savedInstanceState);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="Button 按鈕測試"
        android:gravity="center_vertical|center_horizontal" />

    <Button
        android:id="@+id/buttonview0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="這是一個按鈕" />

    <ImageButton
        android:id="@+id/buttonview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/icon" />
</LinearLayout>

5. 輸入框 EditText

登入表單、帳號密碼輸入,幾乎都離不開 EditText。兩個實用小屬性:android:hint 是輸入前的灰色提示文字,android:password="true" 則把輸入內容轉為密碼圓點顯示。

public class EditTextActivity extends Activity {

    Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.editview);
        mContext = this;

        final EditText editText0 = (EditText) findViewById(R.id.editview0);   // 帳號
        final EditText editText1 = (EditText) findViewById(R.id.editview1);   // 密碼
        Button button = (Button) findViewById(R.id.editbutton0);              // 確認鈕

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String username = editText0.getText().toString();
                String password = editText1.getText().toString();
                Toast.makeText(EditTextActivity.this,
                        "使用者名稱:" + username + " 密碼:" + password,
                        Toast.LENGTH_LONG).show();
            }
        });

        super.onCreate(savedInstanceState);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="EditText 輸入框測試"
        android:gravity="center_vertical|center_horizontal" />

    <EditText
        android:id="@+id/editview0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入帳號"
        android:phoneNumber="true" />

    <EditText
        android:id="@+id/editview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入密碼"
        android:password="true" />

    <Button
        android:id="@+id/editbutton0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="確定" />
</LinearLayout>

安全性提醒:範例只是為了示範取值方式,實際產品請勿用 Toast 把密碼明文顯示出來,也別把敏感資訊寫進 Log。

6. 單選 RadioGroup 與 RadioButton

單選的關鍵在容器:用 RadioGroup 包住多個 RadioButton,同一組內只能有一個被選中。監聽 RadioGroup 的 OnCheckedChangeListener,就能取得被按下那個按鈕的 ID。

public class RadioActivity extends Activity {

    Context mContext = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.radioview);
        mContext = this;

        // 單選組一(同一組內只能選一個)
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radion0);
        final RadioButton radioButton0 = (RadioButton) findViewById(R.id.radionButton0);
        final RadioButton radioButton1 = (RadioButton) findViewById(R.id.radionButton1);
        final RadioButton radioButton2 = (RadioButton) findViewById(R.id.radionButton2);

        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkID) {
                if (radioButton0.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第一組" + radioButton0.getText(),
                            Toast.LENGTH_LONG).show();
                } else if (radioButton1.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第一組" + radioButton1.getText(),
                            Toast.LENGTH_LONG).show();
                } else if (radioButton2.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第一組" + radioButton2.getText(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        // 單選組二
        RadioGroup radioGroup0 = (RadioGroup) findViewById(R.id.radion1);
        final RadioButton radioButton3 = (RadioButton) findViewById(R.id.radionButton3);
        final RadioButton radioButton4 = (RadioButton) findViewById(R.id.radionButton4);
        final RadioButton radioButton5 = (RadioButton) findViewById(R.id.radionButton5);

        radioGroup0.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int checkID) {
                if (radioButton3.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第二組" + radioButton3.getText(),
                            Toast.LENGTH_LONG).show();
                } else if (radioButton4.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第二組" + radioButton4.getText(),
                            Toast.LENGTH_LONG).show();
                } else if (radioButton5.getId() == checkID) {
                    Toast.makeText(RadioActivity.this,
                            "您選中了第二組" + radioButton5.getText(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });

        super.onCreate(savedInstanceState);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="單項選擇測試第一組"
        android:gravity="center_vertical|center_horizontal" />

    <RadioGroup
        android:id="@+id/radion0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/radionButton0"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item0" />

        <RadioButton
            android:id="@+id/radionButton1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item1" />

        <RadioButton
            android:id="@+id/radionButton2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item2" />
    </RadioGroup>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="單項選擇測試第二組"
        android:gravity="center_vertical|center_horizontal" />

    <RadioGroup
        android:id="@+id/radion1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/radionButton3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item3" />

        <RadioButton
            android:id="@+id/radionButton4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item4" />

        <RadioButton
            android:id="@+id/radionButton5"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="item5" />
    </RadioGroup>
</LinearLayout>

7. 多選 CheckBox

CheckBox 允許多選,因此不能像 RadioButton 那樣只記住「當前選項」。這裡的做法是用一個清單收集被勾選的文字,勾選時加入、取消時移除,按下確定鈕再一次顯示結果。

public class CheckboxActivity extends Activity {

    // 用來儲存被勾選的內容
    ArrayList<String> item = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.checkboxview);

        CheckBox checkbox0 = (CheckBox) findViewById(R.id.checkboxview0);
        CheckBox checkbox1 = (CheckBox) findViewById(R.id.checkboxview1);
        CheckBox checkbox2 = (CheckBox) findViewById(R.id.checkboxview2);
        CheckBox checkbox3 = (CheckBox) findViewById(R.id.checkboxview3);
        Button button = (Button) findViewById(R.id.checkboxbutton);

        // 對每個 CheckBox 掛上監聽
        checkbox0.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean arg1) {
                String str = button.getText().toString();
                if (button.isChecked()) {
                    item.add(str);
                } else {
                    item.remove(str);
                }
            }
        });

        checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean arg1) {
                String str = button.getText().toString();
                if (button.isChecked()) {
                    item.add(str);
                } else {
                    item.remove(str);
                }
            }
        });

        checkbox2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean arg1) {
                String str = button.getText().toString();
                if (button.isChecked()) {
                    item.add(str);
                } else {
                    item.remove(str);
                }
            }
        });

        checkbox3.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton button, boolean arg1) {
                String str = button.getText().toString();
                if (button.isChecked()) {
                    item.add(str);
                } else {
                    item.remove(str);
                }
            }
        });

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                String str = item.toString();
                Toast.makeText(CheckboxActivity.this,
                        "您選中了" + str, Toast.LENGTH_LONG).show();
            }
        });

        super.onCreate(savedInstanceState);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:textColor="#000000"
        android:textSize="18dip"
        android:background="#00FF00"
        android:text="多項選擇測試"
        android:gravity="center_vertical|center_horizontal" />

    <CheckBox
        android:id="@+id/checkboxview0"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="item0" />

    <CheckBox
        android:id="@+id/checkboxview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="item1" />

    <CheckBox
        android:id="@+id/checkboxview2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="item2" />

    <CheckBox
        android:id="@+id/checkboxview3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="item3" />

    <Button
        android:id="@+id/checkboxbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="確定" />
</LinearLayout>

四段幾乎一模一樣的監聽程式碼其實可以抽成一個匿名內部類別或共用方法來減少重複;這裡刻意保持直白,方便對照理解每個 CheckBox 各自獨立運作。另外,若使用較新的元件庫,也可以考慮用 setOnCheckedChangeListener 搭配 lambda 表達式讓程式碼更精簡。

整理一下這七個控件

TextView 負責顯示、EditText 負責輸入、Button 與 ImageButton 負責觸發動作、RadioGroup 處理互斥的單選、CheckBox 處理可並存的多選、Menu 提供情境式的操作入口、WebView 則是原生與網頁內容之間的橋樑。把這七個玩熟,一般的表單頁、設定頁、列表頁基本都能應付;接下來再往自訂 View 與 RecyclerView 等進階主題推進,會順手很多。

原始碼下載:https://download.csdn.net/source/3449861

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved