編輯:關於 Android 程式設計
上一篇把骨架、測量、佈局與觸控都搭好了,這篇來補上剩下幾個關鍵環節:動畫驅動、效能優化、跨頁預繪製,以及底部指示點。
在 ViewGroup 中實作對頁:
public void snapToScreen(int whichScreen) {
whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));
boolean changingScreens = whichScreen != mCurrentScreen;
mNextScreen = whichScreen;
int mScrollX = this.getScrollX();
final int newX = whichScreen * getWidth();
final int delta = newX - mScrollX;
// 從 x 座標 mScrollX 的位置滑動 delta 距離
mScroller.startScroll(mScrollX, 0, delta, 0, Math.abs(delta) * 2);
// invalidate 非常重要,否則輕微移動後頁面無法復原
invalidate();
}
只呼叫 startScroll 是不夠的,必須搭配 computeScroll 才有連續的位移效果:
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
} else if (mNextScreen != -1) {
// 滑動完成後才執行這裡,此時必須設定當前頁
setCurrentScreen(Math.max(0, Math.min(mNextScreen, getChildCount() - 1)));
mNextScreen = -1;
}
}
如果一次載入太多子控制項,效能會明顯下降。解法是只顯示當前頁,其餘設為不可見:
void setCurrentScreen(int index) {
mCurrentScreen = index;
resetVisibilityForChildren();
}
private void resetVisibilityForChildren() {
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (Math.abs(mCurrentScreen - i) <= 0) {
child.setVisibility(View.VISIBLE);
} else {
child.setVisibility(View.INVISIBLE);
}
}
}
既然非當前頁被設為不可見,滑動過程中就會出現空白。解法是在繪製階段主動把左右兩頁都畫上:
@Override
protected void dispatchDraw(Canvas canvas) {
int childCount = getChildCount();
if (childCount == 0) {
return;
}
boolean restore = false;
int restoreCount = 0;
final long drawingTime = getDrawingTime();
final float scrollPos = (float) getScrollX() / getWidth();
final int leftScreen = (int) scrollPos;
final int rightScreen = leftScreen + 1;
if (leftScreen >= 0 && leftScreen < childCount) {
// 這會讓 leftScreen 從不可見狀態顯示出來
drawChild(canvas, getChildAt(leftScreen), drawingTime);
}
if (rightScreen < getChildCount()) {
drawChild(canvas, getChildAt(rightScreen), drawingTime);
}
if (restore) {
canvas.restoreToCount(restoreCount);
}
}
先在 MyGroup 類裡定義回呼介面與更新邏輯:
public void setmListener(OnViewChangedListener mListener) {
this.mListener = mListener;
}
public interface OnViewChangedListener {
/**
* 視圖切換時回呼。
* @param viewIndex 索引
*/
void onViewChanged(int viewIndex);
}
private static final int DEFAULT_POINT_MARGIN = 5;
/**
* 更新指示點狀態,包括總數與當前位置。
*
* @param dotsLayout 用來放置指示點的 layout
* @param total 總數
* @param current 當前位置
* @param state Bundle 參數擴展,可為 null
*/
public static void updateDots(ViewGroup dotsLayout, int total, int current, Bundle state) {
if (total < 0) {
total = 0;
}
int lastIndex = -1;
Object tag = dotsLayout.getTag(R.id.dots_current);
if (tag != null) {
lastIndex = (Integer) tag;
}
int margin = DEFAULT_POINT_MARGIN;
if (state != null) {
margin = state.getInt(KEY_POINT_MARGIN, margin);
}
int childrenNum = dotsLayout.getChildCount();
for (int i = childrenNum; i < total; i++) {
ImageView pointView = new ImageView(dotsLayout.getContext());
pointView.setImageResource(R.drawable.dot);
dotsLayout.addView(pointView);
LinearLayout.LayoutParams params =
(LinearLayout.LayoutParams) pointView.getLayoutParams();
params.leftMargin = margin;
params.rightMargin = margin;
}
for (int i = childrenNum - 1; i >= total; i--) {
dotsLayout.removeViewAt(i);
}
if (current == lastIndex) {
return;
}
if (lastIndex >= 0 && lastIndex < total) {
ImageView pointView = (ImageView) dotsLayout.getChildAt(lastIndex);
pointView.setImageResource(R.drawable.dot);
}
if (current >= 0 && current < total) {
ImageView pointView = (ImageView) dotsLayout.getChildAt(current);
pointView.setImageResource(R.drawable.dot_current);
}
dotsLayout.setTag(R.id.dots_current, current);
}
public interface WorkspaceSnapListener {
void onSnapToScreen(MyGroup workspace, int whichScreen);
}
public void setSnapListener(WorkspaceSnapListener listener) {
snapListener = listener;
}
接著在兩個時機點觸發回呼:
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
// ...
} else if (mNextScreen != -1) {
if (mListener != null) {
mListener.onViewChanged(mCurrentScreen);
}
}
}
public void snapToScreen(int whichScreen) {
if (snapListener != null) {
snapListener.onSnapToScreen(this, whichScreen);
}
// ...
}
<FrameLayout android:id="@+id/MainRoot"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="https://schemas.android.com/apk/res/android">
<com.ringcentral.android.utils.ui.widget.mygroup
android:background="@drawable/help_background_selector"
android:id="@+id/workspace"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<LinearLayout android:id="@+id/dots_layout"
android:layout_gravity="bottom|center_horizontal"
android:layout_height="wrap_content"
android:layout_marginbottom="28dip"
android:layout_width="wrap_content"
android:orientation="horizontal" />
</com.ringcentral.android.utils.ui.widget.mygroup>
</FrameLayout>
指示點的形狀定義:
<shape android:shape="oval"
xmlns:android="https://schemas.android.com/apk/res/android">
<size android:height="6dip" android:width="6dip" />
<solid android:color="#7fffffff" />
</shape>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
final ViewGroup dotsLayout = (ViewGroup) findViewById(R.id.dots_layout);
final int[] images = new int[]{
R.drawable.help_01, R.drawable.help_02, R.drawable.help_03
};
final MyGroup myGroup = (MyGroup) findViewById(R.id.workspace);
final Bundle dotsState = new Bundle();
int margin = getResources().getDimensionPixelSize(R.dimen.workspace_dot_margin);
dotsState.putInt(MyGroup.KEY_POINT_MARGIN, margin);
MyGroup.updateDots(dotsLayout, images.length, 0, dotsState);
for (int i = 0; i < 3; i++) {
final View item = getLayoutInflater().inflate(R.layout.introduction_item_test, null);
myGroup.addView(item);
final ImageView imageView = (ImageView) item.findViewById(R.id.introduction_image_view);
try {
imageView.setImageResource(images[i]);
} catch (OutOfMemoryError e) {
// 圖片過大時保護
}
}
myGroup.setmListener(new OnViewChangedListener() {
@Override
public void onViewChanged(int viewIndex) {
myGroup.updateDots(dotsLayout, images.length, viewIndex, dotsState);
}
});
myGroup.setSnapListener(new WorkspaceSnapListener() {
@Override
public void onSnapToScreen(MyGroup workspace, int whichScreen) {
myGroup.updateDots(dotsLayout, images.length, whichScreen, dotsState);
}
});
}
效果圖:

仔細看這套實作,有兩個設計值得借鏡:一是用 INVISIBLE 而非 GONE 來隱藏非當前頁,因為 GONE 會讓子 View 不參與佈局,座標計算會出錯;二是把「頁面切換」與「滑動對齊」拆成兩個監聽器,前者在動畫結束後觸發、後者在對頁開始時觸發,這樣指示點的更新時機就能精準對應使用者的視覺感受。
u-boot 串口與 stdio、console 初始化及相關操作詳解(三)
console 是構建在 stdio 之上的,console 的初始化是 board_r 中最後收尾的操作。 console 的初始化函數 console_init_r
Android 6.0 Marshmallow 新特性與開發重點
Android 6.0 Marshmallow 是 Android 發展中的一個重要版本,它帶來了執行期權限、電力優化、應用待命與部分 API 調整等變化。開發者在升級或
Android Dagger 依賴注入框架入門:概念、環境配置與常見規則
第一次接觸 Dagger 這套 Android 依賴注入(DI)框架時,會覺得它跟 Spring 的 IoC 概念很像。但兩者有個關鍵差異:Spring 依靠執行期反射完
Android 圖像處理大全:圓角、黑白、模糊、浮雕、哈哈鏡等十一種特效實作
前陣子在 GitHub 上無意間挖到一份相當完整的圖像處理原始碼(可惜連結已經找不回來了),閒著沒事就整理出來跟大家分享,這裡也要感謝原作者的無私開源。至於圖片的翻轉、傾