android中当系统自带的控件无法满足用户的需求时,可以通过自定义的方式
下面通过代码实现对Button按钮自定义点击效果
MainActivity:
package com.example.kanzaki.learnmyskin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity-main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.kanzaki.learnmyskin.MainActivity">
<!-- 可以直接通过设置background加载自定义的皮肤-->
<Button
android:background="@drawable/button_skin"
android:text="@string/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
在drawable文件夹中创建button-style用于设置Button按钮的静止皮肤
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--填充颜色-->
<solid android:color="@color/colorPrimary" />
<!--设置控件圆角-->
<corners android:radius="5dp" />
</shape>
在drawable文件夹中创建button-style-another用于设置Button按钮的点击时皮肤
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--填充颜色-->
<solid android:color="@color/colorAccent" />
<!--设置控件圆角-->
<corners android:radius="5dp" />
</shape>
在drawable文件夹中创建button-skin用于加载先前设置的两个皮肤
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 设置点击效果-->
<item android:state_pressed="false" android:drawable="@drawable/button_style" />
<item android:state_pressed="true" android:drawable="@drawable/button_style_another" />
</selector>