編輯:關於 Android 程式設計
在 Android 中自定義 Button 按鈕,主要可以分成兩種形式:
本文先介紹第二種做法,也就是純粹用 XML 來定義按鈕外觀,之後再補上封裝自定義 Button 類別的部分。
先在版面檔中放兩個按鈕,一個套用自定義樣式,一個保留系統原始樣式作為對照:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="測試按鈕"
android:background="@drawable/button_style"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="原始按鈕"
/>
</LinearLayout>
對應的 Activity 只需載入這個版面即可:
package com.example.blueapp;
import android.app.Activity;
import android.os.Bundle;
public class TestcActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testc);
}
}
關鍵在於使用 selector 標籤,為按鈕的不同狀態定義各自的 shape:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<gradient android:startColor="#0d76e1" android:endColor="#0d76e1"
android:angle="270" />
<stroke android:width="1dip" android:color="#f403c9" />
<corners android:radius="2dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
</item>
<item android:state_focused="true">
<shape>
<gradient android:startColor="#ffc2b7" android:endColor="#ffc2b7"
android:angle="270" />
<stroke android:width="1dip" android:color="#f403c9" />
<corners android:radius="2dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient android:startColor="#000000" android:endColor="#ffffff"
android:angle="180" />
<stroke android:width="1dip" android:color="#f403c9" />
<corners android:radius="5dip" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
</item>
</selector>
透過 selector 為 pressed、focused 與預設三種狀態分別設定不同外觀,就能輕鬆做出具有視覺回饋效果的漂亮按鈕。
小米5尊享版與標準版有何差別?規格價格對比
小米5尊享版和標準版有什麼區別?備受期待的小米5於2月24日正式發布,一口氣推出三個版本,分別是標準版、高配版與尊享版。其中標準版與高配版僅記憶體配置不同,而尊享版則在規
Android自定義Button實現長按連續響應
本文為大家分享一個自定義Button實現長按連續響應的實例,供感興趣的讀者參考。 在電商類App的購物車頁面,常有這樣的需求:長按「+」或「-」按鈕時,商品數量能連續地增
Android 開發中那個低調的 Service 詳解
「锲而捨之,朽木不折;锲而不捨,金石可鏤。」——荀況今天學習了 Service 的用法,就和大家一起聊聊 Android 中 Service 的相關知識點。如有謬誤,歡迎
Android 提示微技巧:你真的了解 Dialog、Toast 和 Snackbar 嗎?
Dialog 和 Toast 大家肯定都不陌生,平時實在是用得太多了。而 Snackbar 是 Design Support 庫中提供的新控件,有些朋友可能已經用過,有些