Giới thiệu
Ví dụ này minh họa cách tạo Button hình tròn tùy chỉnh bằng drawable XML selector.
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (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 sử dụng background @drawable/round_button (sẽ tạo ở bước tiếp theo). Kích thước 150dp x 150dp để tạo hình tròn đều.
Bước 3: Tạo drawable tròn (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"/> <!-- Màu vàng khi không nhấn -->
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="#FFF000"/> <!-- Màu cam khi đang nhấn -->
</shape>
</item>
</selector>
shape="oval": Tạo hình elip/tròn (khi width=height sẽ thành tròn)state_pressed: Trạng thái khi người dùng đang nhấn giữsolid color: Màu nền đặc
Bước 4: Activity (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");
}
}
Chạy ứng dụng
Chạy app → Button hình tròn màu vàng xuất hiện. Nhấn giữ Button → Màu chuyển sang cam. Nhả ra → Quay lại vàng.
Mở rộng: Thêm viền (stroke) và shadow
<shape android:shape="oval">
<solid android:color="#FFFF00"/>
<stroke android:width="2dp" android:color="#FF0000"/>
<size android:width="150dp" android:height="150dp"/>
</shape>