Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีสร้างปุ่มวงกลมแบบกำหนดเองใน Android


ตัวอย่าง: การสร้างปุ่มวงกลมแบบกำหนดเอง (Custom Circle Button)

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกรายละเอียดที่จำเป็น

ขั้นตอนที่ 2: จัดการ Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    xmlns:tools="https://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>

ในโค้ดข้างต้น เราใช้ Button พร้อม background เป็น @drawable/round_button ดังนั้นเราต้องสร้างไฟล์ round_button.xml ในโฟลเดอร์ drawable

สร้าง Drawable Resource (res/drawable/round_button.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://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>

ในโค้ดข้างต้น เรากำหนด 2 สถานะ: เมื่อไม่ได้กด (สีเหลือง) และเมื่อกดอยู่ (สีส้ม) รูปทรงเป็น oval (วงกลม/ไข่) ให้ Button

ขั้นตอนที่ 3: เขียนโค้ด Java (src/MainActivity.java)

package com.example.andy.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;

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 คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอ

วิธีสร้างปุ่มวงกลมแบบกำหนดเองใน Android

เมื่อคลิกที่ปุ่ม จะเปลี่ยนสีชั่วคราวขณะกด:

วิธีสร้างปุ่มวงกลมแบบกำหนดเองใน Android