編輯:關於 Android 程式設計

1、繼承 Android 既有的控制項,在原生控制項的基礎上擴充功能與邏輯。
2、繼承 ViewGroup,這類控件可以往自己的版面裡塞進子控件。
3、繼承 View,這類控件與原生控件相似度低,也不需要容納子控件。
ToggleView 在外觀與滑動手感上都跟原生控件沒什麼相似之處,也不需要承載子 View,因此我們選擇繼承 View。
自定義控件一樣要覆寫三個建構子,分別對應不同的使用情境:
// 在版面中使用該控件,並且指定了 style 屬性時呼叫 public ToggleView(Context context, AttributeSet attrs, int defStyle); // 在版面中使用該控件時呼叫 public ToggleView(Context context, AttributeSet attrs); // 在 Java 程式碼中直接 new 出來時呼叫 public ToggleView(Context context);
既然是自己寫的控件,屬性當然自己定義比較順手。這裡需要三個:背景圖、滑塊圖片,以及版面中預設的開關狀態。在 values 目錄下新增 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="toggle">
<attr name="switchBackground" format="reference" />
<attr name="slidingBackground" format="reference" />
<attr name="toggleState" format="boolean" />
</declare-styleable>
</resources>
<declare-styleable> 的 name 屬性決定你在 R 檔案中查到的名稱;每個 <attr> 寫一個屬性,name 是屬性名、format 是型別。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:hss="https://schemas.android.com/apk/res/com.hss.toggle"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.hss.toggle.ToggleView
android:id="@+id/toggleView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
hss:switchBackground="@drawable/switch_background"
hss:slidingBackground="@drawable/slide_button_background"
hss:toggleState="true" >
</com.hss.toggle.ToggleView>
</RelativeLayout>
注意:有些屬性以 android 開頭、有些以 hss 開頭,差別就在於第二行的命名空間宣告:
xmlns:hss="https://schemas.android.com/apk/res/com.hss.toggle"
有了這行,attrs.xml 裡的每個條目都被引入,就能直接使用自訂屬性了。
依命名空間與屬性名稱取值:
String namespace = "https://schemas.android.com/apk/res/com.hss.toggle"; int toggle_switchbackground = attrs.getAttributeResourceValue(namespace, "switchBackground", -1); int toggle_slidingbackground = attrs.getAttributeResourceValue(namespace, "slidingBackground", -1); toggle_state = attrs.getAttributeBooleanValue(namespace, "toggleState", false);
由於用到了 attrs 參數,所以讀取屬性的動作必須放在兩個參數的那個建構子裡。
package com.hss.toggle;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
* 自定義開關控件
*/
public class ToggleView extends View {
private static final String TAG = "ToogleView";
private Bitmap sliding_background;
private Bitmap switch_background;
private boolean isSliding = false;
private boolean toggle_state = false;
private int downX;
private OnToggleStateChangeListener mToggleStateChangeListener;
// 在 xml 中布局並指定 style 時呼叫
public ToggleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
// 在 xml 中布局但未指定 style 時呼叫
public ToggleView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
// 取得 xml 中自訂屬性對應的值
String namespace = "https://schemas.android.com/apk/res/com.hss.toggle";
int toggle_switchbackground = attrs.getAttributeResourceValue(namespace, "switchBackground", -1);
int toggle_slidingbackground = attrs.getAttributeResourceValue(namespace, "slidingBackground", -1);
toggle_state = attrs.getAttributeBooleanValue(namespace, "toggleState", false);
Log.i(TAG, "" + toggle_slidingbackground + " " + toggle_switchbackground);
setToggleSwitchBackground(toggle_switchbackground);
setToggleSlidingBackground(toggle_slidingbackground);
setToggleState(toggle_state);
}
// 在程式碼中 new 時呼叫
public ToggleView(Context context) {
this(context, null);
}
/** 為滑塊設定背景圖片 */
private void setToggleSlidingBackground(int toggle_slidingbackground) {
sliding_background = BitmapFactory.decodeResource(getResources(), toggle_slidingbackground);
}
/** 為背景設定圖片 */
private void setToggleSwitchBackground(int toggle_switchbackground) {
switch_background = BitmapFactory.decodeResource(getResources(), toggle_switchbackground);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 把控件大小設為背景圖片的大小
setMeasuredDimension(switch_background.getWidth(), switch_background.getHeight());
}
@Override
protected void onDraw(Canvas canvas) {
// 先畫背景
canvas.drawBitmap(switch_background, 0, 0, null);
if (isSliding) {
// 滑動狀態:相對左邊的距離 = 目前觸控 x - 滑塊寬度的一半
int left = downX - sliding_background.getWidth() / 2;
// 最大滑動距離 = 背景寬 - 滑塊寬
int rightAlign = switch_background.getWidth() - sliding_background.getWidth();
if (left < 0) {
left = 0;
} else if (left > rightAlign) {
left = rightAlign;
}
canvas.drawBitmap(sliding_background, left, 0, null);
} else {
// 非滑動狀態:依開關狀態決定滑塊位置
if (toggle_state) {
int left = switch_background.getWidth() - sliding_background.getWidth();
canvas.drawBitmap(sliding_background, left, 0, null);
} else {
canvas.drawBitmap(sliding_background, 0, 0, null);
}
}
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
isSliding = true;
downX = (int) event.getX();
break;
case MotionEvent.ACTION_MOVE:
downX = (int) event.getX();
break;
case MotionEvent.ACTION_UP:
downX = (int) event.getX();
isSliding = false;
// 以背景圖片的中線作為判斷依據
int center = switch_background.getWidth() / 2;
boolean state = downX > center;
// 狀態改變時通知監聽者
if (toggle_state != state) {
toggle_state = state;
if (null != mToggleStateChangeListener) {
mToggleStateChangeListener.onToggleState(toggle_state);
}
}
break;
}
// 觸發一次重繪
invalidate();
return true;
}
/** 設定監聽 */
public void setOnToggleStateLinstener(OnToggleStateChangeListener listen) {
mToggleStateChangeListener = listen;
}
public void setToggleState(boolean b) {
toggle_state = b;
}
/** 狀態變更回呼介面 */
public interface OnToggleStateChangeListener {
public void onToggleState(boolean state);
}
}
package com.hss.toggle;
import android.app.Activity;
import android.os.Bundle;
import com.hss.toggle.ToggleView.OnToggleStateChangeListener;
import com.hss.toggle.utils.ToastUtil;
public class MainActivity extends Activity {
private ToggleView toggleView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleView = (ToggleView) findViewById(R.id.toggleView);
toggleView.setOnToggleStateLinstener(new OnToggleStateChangeListener() {
@Override
public void onToggleState(boolean state) {
showToast(state);
}
});
}
// 這裡用到自己封裝的 Toast 工具類
private void showToast(boolean state) {
ToastUtil.makeSuddenlyToast(getApplicationContext(), state ? "開" : "關");
}
}
package com.hss.toggle.utils;
import android.content.Context;
import android.widget.Toast;
/**
* Toast 工具類
*/
public class ToastUtil {
private static Toast toast;
/** 短時間顯示 */
public static void makeShortToast(Context context, String text) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
}
/** 長時間顯示 */
public static void makeLongToast(Context context, String text) {
toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}
/** 單例 Toast,避免連續觸發時排隊 */
public static void makeSuddenlyToast(Context context, String text) {
if (toast == null) {
toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
}
toast.setText(text);
toast.show();
}
}
1、在 values/attrs.xml 中定義自訂屬性與屬性值的型別。
2、撰寫自定義控件類別,繼承 View、ViewGroup 或原生控件,在建構子中取得自訂屬性的值,並實作對應的繪圖與觸摸邏輯。
3、在版面檔案中使用自定義控件與自定義屬性(注意命名空間)。
4、在 Activity 中宣告並設定監聽。
以上就是滑動開關 ToggleView 的完整實作,希望對你的 Android 開發有所幫助。
Android 7.0 MessageQueue 深層解析:Java 與 Native 雙層訊息機制
為什麼 MessageQueue 不只是 Java 層的資料 Android 的訊息處理機制常由 Handler、Looper 與 MessageQueue 組成。表面上
Android 入門:TabHost 與 TabWidget 實例解析
本文介紹 Android 的 Tab 控件。Tab 能起到分頁效果,讓單個螢幕容納更豐富的內容,但相對地也會增加開發的複雜度,建議在有真正需要時才使用。 Android
Android 網絡請求入門:GET 與 POST 的兩種寫法
做 Android 網絡請求,最直觀的兩種方式就是 GET 和 POST。下面用同一個接口(有道翻譯開放 API)分別演示,方便對比差異。 一、GET:參數拼在 URL
Android JNI 入門:用 C 語言實作字串加密與解密
為什麼使用 JNI 做加密 Java 層的加密邏輯容易被反編譯分析,若希望提高逆向成本,可把部分關鍵處理放到 C 語言中,再透過 JNI 與 Java 互動。這樣的架構適