Step1 設計Button樣式,並將圖片放到drawable資料夾裡
初始樣式(btn_default.png):按下去的樣式(btn_pressed.png):
將這兩張圖片放到drawable的資料夾裡
Step2 在drawable資料夾裡新增btn.xml
程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<selector xmlns:android="http://schemas.android.com/apk/res/android"> | |
<item android:state_window_focused="false" android:state_enabled="true" | |
android:drawable="@drawable/btn_default" /> | |
<item android:state_window_focused="false" android:state_enabled="false" | |
android:drawable="@drawable/btn_default" /> | |
<item android:state_pressed="true" | |
android:drawable="@drawable/btn_pressed" /> | |
<item android:state_focused="true" android:state_enabled="true" | |
android:drawable="@drawable/btn_pressed" /> | |
<item android:state_enabled="true" | |
android:drawable="@drawable/btn_default" /> | |
<item android:state_focused="true" | |
android:drawable="@drawable/btn_pressed" /> | |
</selector> |
Step3 在activity_main.xml裡新增Button元件
程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Button | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:background="@drawable/btn" | |
android:text="Button" | |
android:textColor="#fff" /> |
執行時,發現這按鈕太肥大了
可以 把Button的padding設為0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Button | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:background="@drawable/btn" | |
android:text="Button" | |
android:textColor="#fff" | |
android:padding="0dp"/> |
或者 自己設定Button的高度
但執行時Button的字沒有顯示出來...
不過只要也將Button的padding設為0就可以了
所以如果將Button設為指定高度,發現Button的字無法顯示,記得也要將padding設為0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Button | |
android:layout_width="match_parent" | |
android:layout_height="60dp" | |
android:background="@drawable/btn" | |
android:text="Button" | |
android:textColor="#fff" | |
android:padding="0dp"/> |
最終執行結果:
留言
張貼留言