如何在Android中建立自定義圓形按鈕?


此示例演示如何在Android中建立自定義圓形按鈕。

步驟1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟2 − 將以下程式碼新增到res/layout/actiivity_main.xml。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <Button
      android:id = "@+id/text"
      android:textSize = "18sp"
      android:textAlignment = "center"
      android:background = "@drawable/round_button"
      android:layout_width = "150dp"
      android:textColor = "#000"
      android:layout_height = "150dp" />
</LinearLayout>

在上面的程式碼中,我們使用了一個名為round_button的背景來建立圓形按鈕。因此,在drawable資料夾中建立round_button.xml檔案並新增以下程式碼。

<?xml version = "1.0" encoding = "utf-8"?>
<selector xmlns:android = "http://schemas.android.com/apk/res/android">
   <item android:state_pressed = "false">
      <shape android:shape = "oval">
         <solid android:color = "#ffff00"/>
      </shape>
   </item>
   <item android:state_pressed = "true">
      <shape android:shape = "oval">
         <solid android:color = "#fff000"/>
      </shape>
   </item>
</selector>

在上面的程式碼中,我們定義了按鈕的按下和釋放兩種狀態。當用戶點選按鈕時,它會根據按鈕的狀態提供相應的形狀。

步驟3 − 將以下程式碼新增到src/MainActivity.java

package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   Button button;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      button = findViewById(R.id.text);
      button.setText("Button");
   }
}

讓我們嘗試執行您的應用程式。我假設您已將您的Android移動裝置連線到您的電腦。要在Android Studio中執行應用程式,請開啟專案中的一個activity檔案,然後單擊工具欄中的執行圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 −

在上面的結果中,它顯示了預設螢幕,點選按鈕,它將更改按鈕的顏色,如下所示 -

點選 此處 下載專案程式碼

更新於:2019年7月30日

5K+ 瀏覽量

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.