Android - 自定义按钮(Button)点击、获取焦点的背景

准备

IDE:

Android Studio 4.1.1
Build #AI-201.8743.12.41.6953283, built on November 5, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0

Android Virtual Devices:

Name: Pixel_2_API_28
CPU/ABI: Google Play Intel Atom (x86)
Path: C:\Users\86188\.android\avd\Pixel_2_API_28.avd
Target: google_apis_playstore [Google Play] (API level 28)
Skin: pixel_2
SD Card: 512M
fastboot.chosenSnapshotFile: 
runtime.network.speed: full
hw.accelerometer: yes
hw.device.name: pixel_2
hw.lcd.width: 1080
hw.initialOrientation: Portrait
image.androidVersion.api: 28
tag.id: google_apis_playstore
hw.mainKeys: no
hw.camera.front: emulated
avd.ini.displayname: Pixel 2 API 28
hw.gpu.mode: auto
hw.ramSize: 1536
PlayStore.enabled: true
fastboot.forceColdBoot: no
hw.cpu.ncore: 4
hw.keyboard: yes
hw.sensors.proximity: yes
hw.dPad: no
hw.lcd.height: 1920
vm.heapSize: 256
skin.dynamic: yes
hw.device.manufacturer: Google
hw.gps: yes
hw.audioInput: yes
image.sysdir.1: system-images\android-28\google_apis_playstore\x86\
showDeviceFrame: yes
hw.camera.back: virtualscene
AvdId: Pixel_2_API_28
hw.lcd.density: 420
hw.arc: false
hw.device.hash2: MD5:55acbc835978f326788ed66a5cd4c9a7
fastboot.forceChosenSnapshotBoot: no
fastboot.forceFastBoot: yes
hw.trackBall: no
hw.battery: yes
hw.sdCard: yes
tag.display: Google Play
runtime.network.latency: none
disk.dataPartition.size: 6442450944
hw.sensors.orientation: yes
avd.ini.encoding: UTF-8
hw.gpu.enabled: yes

注意:以下示例仅在安卓虚拟设备上运行测试,并没有在真实的设备上运行测试。

自定义按钮(Button)点击、获取焦点的背景

在这里插入图片描述

新建项目,选择 Empty Activity,在配置项目时,Minimum SDK 选择 API 16: Android 4.1 (Jelly Bean)

编辑 src\main\AndroidManifest.xml 应用清单文件,修改应用主题(第 5 行):

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <application
        ...
        android:theme="@style/Theme.AppCompat.NoActionBar">
        ...
    </application>
</manifest>

新增 src\main\res\drawable\button_state_pressed.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <solid android:color="#00000000" />
    <stroke android:width="1dp" android:color="#00FF00" />
</shape>

新增 src\main\res\drawable\button_state_focused.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp" />
    <solid android:color="#00000000" />
    <stroke android:width="1dp" android:color="#0000FF" />
</shape>

新增 src\main\res\drawable\button_state_default.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"> <!-- A rectangle that fills the containing View. This is the default shape. -->

    <!-- Creates rounded corners for the shape. Applies only when the shape is a rectangle. -->
    <!-- android:radius
            Dimension. The radius for all corners, as a dimension value or dimension resource. -->
    <corners android:radius="5dp" />

    <!-- A solid color to fill the shape. -->
    <!-- android:color
            Color. The color to apply to the shape, as a hexadecimal value or color resource. -->
    <solid android:color="#00000000" />

    <!-- A stroke line for the shape. -->
    <!-- android:width
            Dimension. The thickness of the line, as a dimension value or dimension resource. -->
    <!-- android:color
            Color. The color of the line, as a hexadecimal value or color resource. -->
    <stroke android:width="1dp" android:color="#FF0000" />
</shape>

新增 src\main\res\drawable\button_custom.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_state_pressed"
        android:state_pressed="true" />
    <item android:drawable="@drawable/button_state_focused"
        android:state_focused="true" />
    <item android:drawable="@drawable/button_state_default" />
</selector>

编辑 src\main\res\layout\activity_main.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:hint="按 Tab 键,将焦点切换到按钮上,注意观察"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:background="@drawable/button_custom"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />
</androidx.constraintlayout.widget.ConstraintLayout>

编辑 MainActivity 文件:

package com.mk;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                Toast.makeText(MainActivity.this, "On Click", Toast.LENGTH_SHORT).show();
            }
        });
        button.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    
    
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
    
    
                if (hasFocus)
                    Toast.makeText(MainActivity.this, "On Focus", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

参考

Buttons - Custom background

App resources - Resource types - Drawable - Shape drawable

App resources - Resource types - Drawable - State list

猜你喜欢

转载自blog.csdn.net/qq_29761395/article/details/114233902