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

Android 學習筆記(四):常用基本控制項與視圖整理

編輯:關於 Android 程式設計

一、文字、按鈕與輸入框

這三者關係密切,先看它們的繼承結構:

TextView 是它們的共同祖先,最基礎也最常用:

android:text="文本"
android:textSize="20sp"
android:textColor="#FF0"
android:textStyle="bold"
android:lines="3"                // 固定三行
android:singleLine="true"        // 單行顯示
android:typeface="monospace"     // 字型:normal / sans / serif / monospace
android:clickable="true"

Button 的屬性與 TextView 幾乎相同,差別在於它自帶背景樣式,且天生可點擊。

EditText 是輸入框:

android:hint="請輸入QQ"              // 未輸入時的提示文字
android:editable="true"
android:maxLength="50"            // 限制最大字數
android:inputType="textPassword"  // 決定鍵盤類型與是否遮蔽

inputType 值得多說一句:它同時控制螢幕鍵盤的形態(數字、英文、郵件、電話)與顯示方式(是否顯示為密碼),是輸入體驗的關鍵屬性。

二、選擇型控制項

ToggleButton:開關按鈕

android:textOn="開啟"
android:textOff="關閉"
android:checked="true"

RadioButton:單選框,必須搭配 RadioGroup 才有互斥效果。監聽器要設在 RadioGroup 上:

RadioGroup radioGroup.setOnCheckedChangeListener(listener);
android:checked="true"

CheckBox:多選框,彼此獨立,因此每個 CheckBox 都要各自設定監聽。

練習:ToggleButton 與 CheckBox

public class MainActivity extends Activity {

    private List<String> mChooseData = new ArrayList<String>();

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

        CheckBox aCbx = findViewById(R.id.cbx_apple);
        CheckBox bCbx = findViewById(R.id.cbx_banance);
        CheckBox cCbx = findViewById(R.id.cbx_orange);

        myCheckedChangeListener listener = new myCheckedChangeListener();
        aCbx.setOnCheckedChangeListener(listener);
        bCbx.setOnCheckedChangeListener(listener);
        cCbx.setOnCheckedChangeListener(listener);
    }

    /** 一個監聽器共用,靠 viewId 判斷來源 */
    class myCheckedChangeListener implements OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int id = buttonView.getId();
            String name;
            if (id == R.id.cbx_apple)        name = "蘋果";
            else if (id == R.id.cbx_banance) name = "香蕉";
            else if (id == R.id.cbx_orange)  name = "橘子";
            else return;

            if (isChecked) {
                if (!mChooseData.contains(name)) mChooseData.add(name);
            } else {
                mChooseData.remove(name);
            }
        }
    }

    public void myClick(View v) {
        StringBuilder result = new StringBuilder();
        for (String s : mChooseData) {
            result.append(s);
        }
        Toast.makeText(this, result.toString(), Toast.LENGTH_SHORT).show();
    }
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ToggleButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:textOff="關"
        android:textOn="開" />

    <CheckBox android:id="@+id/cbx_apple"   android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="蘋果" />
    <CheckBox android:id="@+id/cbx_banance" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="香蕉" />
    <CheckBox android:id="@+id/cbx_orange"  android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="橘子" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="myClick"
        android:text="button" />

</LinearLayout>

練習:RadioGroup 與 RadioButton

public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener {

    private RadioButton mARg, mBRg, mCRg;

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

        mARg = findViewById(R.id.rg_a);
        mBRg = findViewById(R.id.rg_b);
        mCRg = findViewById(R.id.rg_c);

        RadioGroup rg = findViewById(R.id.rg);
        rg.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.rg_a) {
            Toast.makeText(this, mARg.getText().toString(), Toast.LENGTH_SHORT).show();
        } else if (checkedId == R.id.rg_b) {
            Toast.makeText(this, mBRg.getText().toString(), Toast.LENGTH_SHORT).show();
        } else if (checkedId == R.id.rg_c) {
            Toast.makeText(this, mCRg.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    }
}
<RadioGroup xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rg"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RadioButton android:id="@+id/rg_a" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="蘋果" />
    <RadioButton android:id="@+id/rg_b" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="香蕉" />
    <RadioButton android:id="@+id/rg_c" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="西瓜" />

</RadioGroup>

三、進度條

沒有進度的(不確定型),三種尺寸靠 style 切換:

style="?android:attr/progressBarStyleLarge"   // 大
style="?android:attr/progressBarStyle"        // 普通
style="?android:attr/progressBarStyleSmall"   // 小

有進度的(確定性),需要加上水平 style 與 max/progress:

style="?android:attr/progressBarStyleHorizontal"
android:progress="80"
android:max="100"

SeekBar:可拖動的進度條,常用於音量、亮度調節

android:max="100"
android:progress="50"

RatingBar:星星評分,最小單位為半顆星

android:numStars="4"
android:rating="3.5"
android:stepSize="0.5"

實際版面:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- 不確定型 -->
    <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ProgressBar style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <ProgressBar style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />

    <!-- 確定性 -->
    <ProgressBar style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent" android:layout_height="wrap_content"
        android:layout_marginTop="10dp" android:max="100" android:progress="80" />

    <!-- 可拖動 -->
    <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content"
        android:max="100" android:progress="40" />

    <!-- 星星 -->
    <RatingBar android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:numStars="4" android:rating="3.5" android:stepSize="0.5" />

</LinearLayout>

四、圖片控制項 ImageView

設定圖片來源,XML 或程式碼皆可:

android:src="@drawable/ic_launcher"

// 程式碼
imageView.setImageResource(resId);
imageView.setImageBitmap(bm);
imageView.setImageDrawable(drawable);

scaleType 決定圖片如何縮放填滿容器,是新手最容易搞錯的屬性:

幾個常用的:

  • center:置中不縮放,超出部分裁掉
  • centerCrop:等比放大到填满容器,多出部分裁掉(最常用於頭圖)
  • centerInside:等比縮放到能完整顯示,比 fitCenter 更保守
  • fitXY:拉伸填满,不保持比例(容易變形)
  • fitCenter / fitStart / fitEnd:等比縮放並對齊指定側
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = findViewById(R.id.iv2);
        imageView.setImageResource(R.drawable.flower);
    }
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv1"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:scaleType="centerCrop"
        android:src="@drawable/flower" />

    <ImageView
        android:id="@+id/iv2"
        android:layout_width="150dp"
        android:layout_height="150dp" />

</LinearLayout>

五、滾動容器

當內容超出螢幕可視範圍時,就需要滾動容器:

  • ScrollView:控制上下滾動
  • HorizontalScrollView:控制左右滾動

關鍵限制:兩者都只能容納一個直接子控制項。若需要多個元素一起滾動,必須先包一層 LinearLayout 當作唯一子節點。

<!-- 水平滾動 -->
<HorizontalScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="Hello world!Hello world!Hello world!..."
            android:textSize="30sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="Hello world!Hello world!"
            android:textColor="#F00"
            android:textSize="30sp" />

    </LinearLayout>
</HorizontalScrollView>

注意包在裡面的 LinearLayout 寬度要設為 wrap_content,否則它只會和螢幕一樣寬,內容根本不會溢出,也就滾不動。

<!-- 垂直滾動 -->
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:lines="10" android:text="Hello world" android:textSize="30sp" />
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:lines="10" android:text="Hello world" android:textColor="#F00" android:textSize="30sp" />
        <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:lines="10" android:text="Hello world" android:textColor="#F00" android:textSize="30sp" />

    </LinearLayout>
</ScrollView>

另外提醒:ListView、RecyclerView、WebView 內部本身已具備滾動能力,不要再包一層 ScrollView,否則手勢會互相搶,滑動體驗變得很差。

六、日期與時間選擇器

DatePicker 與 TimePicker 的用法看一個範例就清楚。這裡的重點是 DatePicker 要用 init() 初始化並綁定監聽,而 TimePicker 可以設定是否使用 24 小時制:

public class MainActivity extends Activity implements DatePicker.OnDateChangedListener {

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

        // 日期
        DatePicker datePicker = findViewById(R.id.datePicker);
        Calendar calendar = Calendar.getInstance(Locale.CHINESE);
        int year  = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day   = calendar.get(Calendar.DAY_OF_MONTH);
        datePicker.init(year, month, day, this);   // 初始化並註冊監聽

        // 時間
        TimePicker timePicker = findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener((view, hourOfDay, minute) ->
                Toast.makeText(MainActivity.this,
                        hourOfDay + "..." + minute, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // 注意 Calendar.MONTH 從 0 開始,顯示時要 +1
        Toast.makeText(this,
                "year:" + year + " month:" + (monthOfYear + 1) + " day:" + dayOfMonth,
                Toast.LENGTH_SHORT).show();
    }
}
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <DatePicker
        android:id="@+id/datePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

最容易在這裡出錯的是月份:Calendar.MONTH 與 onDateChanged 回傳的 monthOfYear 都是從 0 起算,直接顯示會少一個月,記得 +1。

這篇的整理重點

把上面的內容濃縮成幾條容易忘的觀念:

  • Button 與 EditText 都繼承自 TextView,屬性大量共用。
  • RadioButton 必須放在 RadioGroup 裡才有單選語意,監聽設在 Group 上;CheckBox 各自獨立,監聽要分別設。
  • 不確定型 ProgressBar 靠 style 切尺寸,確定性才需要 max 與 progress。
  • ImageView 的 scaleType 決定縮放策略,centerCrop 最常用於需要填滿的圖片區。
  • ScrollView 與 HorizontalScrollView 只能有一個直接子節點,且內部容器的對應尺寸屬性要設對才會滾動。
  • 月份從 0 開始,顯示前務必 +1。

這些都是很基礎的東西,但實務上出問題的比例不低,寫下來當作快速查閱的參考。

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