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

Android 開發筆記 004:六大常用基礎控件使用說明

編輯:關於 Android 開發

Android 開發筆記 004:六大常用基礎控件使用說明

這篇把開發裡最高頻的一批基礎控件集中整理一遍:TextView、EditText、Button/ImageButton、ImageView、RadioButton、CheckBox。每個都按「布局代碼 → 常用屬性 → 代碼綁定與監聽」的順序走。

  • TextView 文本框
  • EditText 輸入框
  • Button 與 ImageButton
  • ImageView
  • RadioButton
  • CheckBox 復選框

TextView 文本框

最基礎的文本顯示控件。

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, MyActivity"
    />

常用屬性:

id:給控件一個標識,之後可以在 Java 代碼裡據此拿到該對象。
layout_width:寬度,一般三種取值——wrap_content 表示按內容撐開,文字越多越寬;match_parent 表示填滿父容器;也可以直接寫具體數值。
layout_height:高度,取值方式同上。
gravity:控件內部內容的對齊方向,也就是文字對齊方式。
text:顯示的文本內容。建議抽到 values/string.xml 再用 @string/xxx 引用,而不是硬寫在布局裡。
textColor:文字顏色。
textStyle:文字風格,三個可選值 normal(常規)、bold(加粗)、italic(斜體)。
background:控件背景色,會鋪滿整個控件。

引用 string.xml 資源的兩步:

第一步,在 res/values/strings.xml 裡添加並命名:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">MyActivity</string>
    <string name="hello">hello,你好</string>
</resources>

第二步,在控件裡引用:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

EditText 輸入框

和 TextView 極為相似,最大的差別是它允許用戶輸入。

<EditText
    android:id="@+id/edit"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    />

常用屬性:

id / layout_width / layout_height:同前。
inputType:鍵盤與輸入模式。設為 textPassword 得到密碼框,設為 phone 得到數字鍵盤。
maxLength:最大輸入字符數,如 android:maxLength="5"。
maxLines / minLines:最大與最小行數。
hint:默認提示文本。
textColorHint:提示文本顏色。
capitalize:英文大小寫規則,sentences 僅首字母大寫、words 單詞首字母大寫、characters 全部大寫。

綁定方式與其他控件一致,在 onCreate 裡用 findViewById:

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 綁定 main.xml 中的 EditText 控件
        EditText editText = (EditText) findViewById(R.id.edit);
    }
}

取用戶輸入用 getText()。這裡有個坑:緊接著綁定語句之後直接調用 getText() 是取不到內容的,因為用戶還沒輸入。必須等一個觸發事件——比如點擊某個按鈕——再去取值:

EditText editText;
TextView text;

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

    editText = (EditText) findViewById(R.id.edit);
    text = (TextView) findViewById(R.id.text);

    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            text.setText(editText.getText());
        }
    });
}

整個流程就是:輸入文本後點擊 text,text 的內容被替換成剛才輸入的內容。

Button 與 ImageButton

兩者用法基本類似,重點講 Button。

<Button
    android:id="@+id/btn"
    android:text="普通按鈕"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

其他常用屬性:background 背景,可以是顏色、圖片或 XML 資源;text 按鈕文字;textColor 文字顏色;textSize 文字大小。

綁定:

btn = (Button) findViewById(R.id.btn);

監聽點擊:

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this, "button 被按下", Toast.LENGTH_SHORT).show();
    }
});

Toast 是那種短暫出現、自動消失的黑色提示框,用來做輕量反饋很合適。完整示例:

public class MainActivity extends Activity {

    private Button btn;

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

        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this, "button 被按下", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

ImageView

顧名思義,用來顯示圖片。

<ImageView
    android:id="@+id/imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_launcher"/>

兩個屬性的差異值得記住:background 設置控件背景,當寬度固定時會拉伸圖片;src 設置控件填充內容,固定寬度時不會拉伸。實戰中顯示圖片一般用 src,background 留給真正的背景。

綁定:

img = (ImageView) findViewById(R.id.imageview);

ImageView 本身沒有什麼監聽方法,常用場景是配合 handler 做圖片輪播,這時會用到換圖方法:

setImageResource(int id):用內部資源替換圖片,參數是 R.drawable.xxx。
setImageBitmap(Bitmap bitmap):用 Bitmap 替換圖片,Bitmap 通常來自網絡下載。

用法:

img.setImageResource(R.mipmap.ic_launcher);

RadioButton 單選按鈕

就是一組選項裡只能選一個。因此必須把 RadioButton 放進 RadioGroup 中,單選功能才成立。

<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <RadioButton
        android:id="@+id/btnMan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="男"
        android:checked="true"/>

    <RadioButton
        android:id="@+id/btnWoman"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="女"/>

</RadioGroup>

監聽挂在 RadioGroup 上,方法叫 setOnCheckedChangeListener()。取選中項的值有兩種路子,第一種是監聽變化:

RadioGroup radgroup = (RadioGroup) findViewById(R.id.radioGroup);

radgroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton radbtn = (RadioButton) findViewById(checkedId);
        Toast.makeText(getApplicationContext(),
                "按鈕組值發生改變,你選了" + radbtn.getText(),
                Toast.LENGTH_LONG).show();
    }
});

操作 RadioButton 相關信息的方法:getChildCount() 取得單選按鈕數目;getChildAt(i) 按索引取得按鈕;isChecked() 判斷是否被選中。

CheckBox 復選框

可以同時選中多項。

<CheckBox
    android:id="@+id/checkbox"
    android:text="蘋果"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<CheckBox
    android:id="@+id/checkbox1"
    android:text="香蕉"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<CheckBox
    android:id="@+id/checkbox2"
    android:text="大鴨梨"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

每個 CheckBox 掛 setOnCheckedChangeListener,點擊時給出反饋;提交時再統一遍歷取值:

public class MyActivity extends Activity
        implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private CheckBox cb_one;
    private CheckBox cb_two;
    private CheckBox cb_three;
    private Button btn_send;

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

        cb_one = (CheckBox) findViewById(R.id.cb_one);
        cb_two = (CheckBox) findViewById(R.id.cb_two);
        cb_three = (CheckBox) findViewById(R.id.cb_three);
        btn_send = (Button) findViewById(R.id.btn_send);

        cb_one.setOnCheckedChangeListener(this);
        cb_two.setOnCheckedChangeListener(this);
        cb_three.setOnCheckedChangeListener(this);
        btn_send.setOnClickListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (compoundButton.isChecked()) {
            Toast.makeText(this, compoundButton.getText().toString(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {
        String choose = "";
        if (cb_one.isChecked()) choose += cb_one.getText().toString() + " ";
        if (cb_two.isChecked()) choose += cb_two.getText().toString() + " ";
        if (cb_three.isChecked()) choose += cb_three.getText().toString() + " ";
        Toast.makeText(this, choose, Toast.LENGTH_SHORT).show();
    }
}

小結一下:這批控件的綁定套路完全一致(findViewById),差別主要在屬性與監聽接口。把 setOnClickListener 與 setOnCheckedChangeListener 這兩個模式記熟,日常的界面交互基本都能應付。

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