按鈕是 App 互動的核心元件。本文將介紹一般 Button 與帶圖片的 ImageButton 用法,包含文字樣式設定、圖片顯示與點擊事件處理。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 按鈕測試"
android:textSize="18sp"
android:textColor="#000000"
android:background="#00FF00"
android:gravity="center" />
<Button
android:id="@+id/buttonview0"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="這是一個按鈕" />
<ImageButton
android:id="@+id/buttonview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:background="@null" />
</LinearLayout>
public class ButtonActivity extends Activity {
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buttonview);
mContext = this;
// 一般按鈕
Button btnNormal = findViewById(R.id.buttonview0);
btnNormal.setTextColor(Color.BLUE);
btnNormal.setTextSize(30);
btnNormal.setOnClickListener(v ->
Toast.makeText(ButtonActivity.this, "您點擊了『這是一個按鈕』", Toast.LENGTH_LONG).show()
);
// 圖片按鈕
ImageButton btnImage = findViewById(R.id.buttonview1);
btnImage.setOnClickListener(v ->
Toast.makeText(ButtonActivity.this, "您點擊了一個帶圖片的按鈕", Toast.LENGTH_LONG).show()
);
}
}
| 屬性/方法 | 說明 |
|---|---|
| android:text | 按鈕顯示文字 |
| android:textColor | 文字顏色 |
| android:textSize | 文字大小 (sp) |
| android:src | ImageButton 圖片來源 |
| android:background | 背景圖片/顏色 (設 @null 移除預設陰影) |
| setOnClickListener | 設定點擊監聽器 |
StateListDrawable (selector) 實現按下/正常/不可用狀態的不同圖片。android:drawableLeft/Right/Top/Bottom 在 Button 內加入圖示。android:onClick 直接在 XML 指定點擊方法 (需在 Activity 定義對應 public 方法)。Button 與 ImageButton 雖然簡單,但透過樣式客製化能打造出符合設計規範的互動元件。建議善用 Selector 處理視覺回饋,提升操作手感。