萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Button 與 ImageButton 按鈕完整使用指南

前言

按鈕是 App 互動的核心元件。本文將介紹一般 Button 與帶圖片的 ImageButton 用法,包含文字樣式設定、圖片顯示與點擊事件處理。

版面配置 (XML)

<?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>

Activity 程式碼實作

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:srcImageButton 圖片來源
android:background背景圖片/顏色 (設 @null 移除預設陰影)
setOnClickListener設定點擊監聽器

進階應用

  • 使用 StateListDrawable (selector) 實現按下/正常/不可用狀態的不同圖片。
  • 搭配 android:drawableLeft/Right/Top/Bottom 在 Button 內加入圖示。
  • 設定 android:onClick 直接在 XML 指定點擊方法 (需在 Activity 定義對應 public 方法)。

總結

Button 與 ImageButton 雖然簡單,但透過樣式客製化能打造出符合設計規範的互動元件。建議善用 Selector 處理視覺回饋,提升操作手感。

copyright © 萬盛學電腦網 all rights reserved