編輯:Android 開發實例
上一篇我們把 Camera 的基本用法過了一遍,並用它做了一個類似 API Demos 中圖片中軸旋轉的示例。但那個例子的核心其實是 API Demos 自帶的 Rotate3dAnimation 類,所有的 Matrix 與 Camera 代碼都被封裝在裡面,我們只是按了按開關。
說心裡不癢癢那是假的。學會了 Camera,卻沒能按自己的思路搆建一套炫的 3D 效果,總覺得差了點什麼。所以這次我們來玩大一點的:做一個推拉門式的立體側滑菜單,而且完全不引用 API Demos 裡的任何代碼,一切都自己寫。
如果你對 Camera 的用法還不太有把握,建議先回去把上一篇補一補。側滑菜單本身我寫過好幾篇,實現套路應該已經不新鮮了,因此本文的重心只有一件事:如何在傳統側滑菜單的骨架上,長出推拉門一般的立體質感。
傳統側滑菜單的做法很樸素:菜單布局藏在左側屏外,主布局蓋在上面,手指拖多遠,主布局就偏移多遠,菜單便一點點露出來。
這次要做出推拉門的錯覺,思路得拐個彎。我們讓真正的菜單保持隱藏,同時把菜單內容「拓印」成一張圖片;手指滑動的過程中,對這張圖片施加三維旋轉,讓它像一扇正在被推開的門;等手勢結束、滾動歸位之後,才把真正的菜單顯示出來,再把那張臨時圖片藏起來。
一句話概括:滑動過程中你看到的不是菜單本身,而是菜單的一張會轉動的「照片」。理解這一點,後面的代碼就都順了。
新建 Android 項目 ThreeDSlidingLayoutDemo,開始動手。
先寫一個繼承自 View 的 Image3dView,它承擔兩件事:把源視圖轉成位圖,以及對這張位圖做三維變換。
public class Image3dView extends View {
/**
* 源視圖,用於生成圖片對象。
*/
private View sourceView;
/**
* 根據傳入的源視圖生成的圖片對象。
*/
private Bitmap sourceBitmap;
/**
* 源視圖的寬度。
*/
private float sourceWidth;
/**
* Matrix 對象,用於對圖片進行矩陣操作。
*/
private Matrix matrix = new Matrix();
/**
* Camera 對象,用於對圖片進行三維操作。
*/
private Camera camera = new Camera();
public Image3dView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 提供外部接口,允許向 Image3dView 傳入源視圖。
*/
public void setSourceView(View view) {
sourceView = view;
sourceWidth = sourceView.getWidth();
}
/**
* 清除掉緩存的圖片對象。
*/
public void clearSourceBitmap() {
if (sourceBitmap != null) {
sourceBitmap = null;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (sourceBitmap == null) {
getSourceBitmap();
}
// 計算圖片需要旋轉的角度
float degree = 90 - (90 / sourceWidth) * getWidth();
camera.save();
camera.rotateY(degree);
camera.getMatrix(matrix);
camera.restore();
// 將旋轉的中心點移動到屏幕左邊緣的中間位置
matrix.preTranslate(0, -getHeight() / 2);
matrix.postTranslate(0, getHeight() / 2);
canvas.drawBitmap(sourceBitmap, matrix, null);
}
/**
* 獲取源視圖對應的圖片對象。
*/
private void getSourceBitmap() {
if (sourceView != null) {
sourceView.setDrawingCacheEnabled(true);
sourceView.layout(0, 0, sourceView.getWidth(), sourceView.getHeight());
sourceView.buildDrawingCache();
sourceBitmap = sourceView.getDrawingCache();
}
}
}
幾個要點值得多說兩句。setSourceView() 是留給外部的入口,稍後要拓印的就是傳進來的這個 View。onDraw() 裡先判斷緩存有沒有失效,沒有的話調 getSourceBitmap() 生成位圖;接著那行 degree 的計算很關鍵——它拿 Image3dView 當前寬度和源視圖總寬度做比例換算,讓旋轉角度隨滑動進度線性變化,從 0 度一路推到接近 90 度。然後 Camera 繞 Y 軸轉,把旋轉中心挪到屏幕左邊緣的垂直中線上,最後 drawBitmap 畫出來。
順帶提醒:clearSourceBitmap() 之所以存在,是因為源視圖的內容會變。每次滑動開始前把舊位圖丟掉,下次繪製時才會重新拓印一份新鮮的。
接下來是菜單本體。代碼確實不短,但骨架和之前的側滑菜單幾乎一致,看過的朋友會覺得很眼熟。
public class ThreeDSlidingLayout extends RelativeLayout implements OnTouchListener {
/**
* 滾動顯示和隱藏左側布局時,手指滑動需要達到的速度。
*/
public static final int SNAP_VELOCITY = 200;
/**
* 滑動狀態的一種,表示未進行任何滑動。
*/
public static final int DO_NOTHING = 0;
/**
* 滑動狀態的一種,表示正在滑出左側菜單。
*/
public static final int SHOW_MENU = 1;
/**
* 滑動狀態的一種,表示正在隱藏左側菜單。
*/
public static final int HIDE_MENU = 2;
/**
* 記錄當前的滑動狀態
*/
private int slideState;
/**
* 屏幕寬度值。
*/
private int screenWidth;
/**
* 右側布局最多可以滑動到的左邊緣。
*/
private int leftEdge = 0;
/**
* 右側布局最多可以滑動到的右邊緣。
*/
private int rightEdge = 0;
/**
* 在被判定為滾動之前用戶手指可以移動的最大值。
*/
private int touchSlop;
private float xDown;
private float yDown;
private float xMove;
private float yMove;
private float xUp;
/**
* 左側布局當前是顯示還是隱藏。只有完全顯示或隱藏時才會更改此值,滑動過程中此值無效。
*/
private boolean isLeftLayoutVisible;
/**
* 是否正在滑動。
*/
private boolean isSliding;
/**
* 是否已加載過一次 layout,這裡 onLayout 中的初始化只需加載一次
*/
private boolean loadOnce;
/**
* 左側布局對象。
*/
private View leftLayout;
/**
* 右側布局對象。
*/
private View rightLayout;
/**
* 在滑動過程中展示的 3D 視圖
*/
private Image3dView image3dView;
/**
* 用於監聽側滑事件的 View。
*/
private View mBindView;
/**
* 左側布局的參數,通過此參數來重新確定左側布局的寬度,以及更改 leftMargin 的值。
*/
private MarginLayoutParams leftLayoutParams;
/**
* 右側布局的參數,通過此參數來重新確定右側布局的寬度。
*/
private MarginLayoutParams rightLayoutParams;
/**
* 3D 視圖的參數,通過此參數來重新確定 3D 視圖的寬度。
*/
private ViewGroup.LayoutParams image3dViewParams;
/**
* 用於計算手指滑動的速度。
*/
private VelocityTracker mVelocityTracker;
public ThreeDSlidingLayout(Context context, AttributeSet attrs) {
super(context, attrs);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
screenWidth = wm.getDefaultDisplay().getWidth();
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
/**
* 綁定監聽側滑事件的 View,即在綁定的 View 進行滑動才可以顯示和隱藏左側布局。
*/
public void setScrollEvent(View bindView) {
mBindView = bindView;
mBindView.setOnTouchListener(this);
}
/**
* 將屏幕滾動到左側布局界面,滾動速度設定為 10。
*/
public void scrollToLeftLayout() {
image3dView.clearSourceBitmap();
new ScrollTask().execute(-10);
}
/**
* 將屏幕滾動到右側布局界面,滾動速度設定為 -10。
*/
public void scrollToRightLayout() {
image3dView.clearSourceBitmap();
new ScrollTask().execute(10);
}
public boolean isLeftLayoutVisible() {
return isLeftLayoutVisible;
}
/**
* 在 onLayout 中重新設定左側布局和右側布局的參數。
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (changed && !loadOnce) {
// 獲取左側布局對象
leftLayout = findViewById(R.id.menu);
leftLayoutParams = (MarginLayoutParams) leftLayout.getLayoutParams();
rightEdge = -leftLayoutParams.width;
// 獲取右側布局對象
rightLayout = findViewById(R.id.content);
rightLayoutParams = (MarginLayoutParams) rightLayout.getLayoutParams();
rightLayoutParams.width = screenWidth;
rightLayout.setLayoutParams(rightLayoutParams);
// 獲取 3D 視圖對象
image3dView = (Image3dView) findViewById(R.id.image_3d_view);
// 將左側布局傳入 3D 視圖中作為生成源
image3dView.setSourceView(leftLayout);
loadOnce = true;
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
createVelocityTracker(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 手指按下時,記錄按下時的橫坐標
xDown = event.getRawX();
yDown = event.getRawY();
slideState = DO_NOTHING;
break;
case MotionEvent.ACTION_MOVE:
// 手指移動時,對比按下時的橫坐標,計算出移動的距離,來調整右側布局的 leftMargin 值
xMove = event.getRawX();
yMove = event.getRawY();
int moveDistanceX = (int) (xMove - xDown);
int moveDistanceY = (int) (yMove - yDown);
checkSlideState(moveDistanceX, moveDistanceY);
switch (slideState) {
case SHOW_MENU:
rightLayoutParams.rightMargin = -moveDistanceX;
onSlide();
break;
case HIDE_MENU:
rightLayoutParams.rightMargin = rightEdge - moveDistanceX;
onSlide();
break;
default:
break;
}
break;
case MotionEvent.ACTION_UP:
xUp = event.getRawX();
int upDistanceX = (int) (xUp - xDown);
if (isSliding) {
// 手指抬起時,進行判斷當前手勢的意圖
switch (slideState) {
case SHOW_MENU:
if (shouldScrollToLeftLayout()) {
scrollToLeftLayout();
} else {
scrollToRightLayout();
}
break;
case HIDE_MENU:
if (shouldScrollToRightLayout()) {
scrollToRightLayout();
} else {
scrollToLeftLayout();
}
break;
default:
break;
}
} else if (upDistanceX < touchSlop && isLeftLayoutVisible) {
scrollToRightLayout();
}
recycleVelocityTracker();
break;
}
if (v.isEnabled()) {
if (isSliding) {
unFocusBindView();
return true;
}
if (isLeftLayoutVisible) {
return true;
}
return false;
}
return true;
}
/**
* 執行滑動過程中的邏輯操作,如邊界檢查,改變偏移值,可見性檢查等。
*/
private void onSlide() {
checkSlideBorder();
rightLayout.setLayoutParams(rightLayoutParams);
image3dView.clearSourceBitmap();
image3dViewParams = image3dView.getLayoutParams();
image3dViewParams.width = -rightLayoutParams.rightMargin;
// 滑動的同時改變 3D 視圖的大小
image3dView.setLayoutParams(image3dViewParams);
// 保證在滑動過程中 3D 視圖可見,左側布局不可見
showImage3dView();
}
/**
* 根據手指移動的距離,判斷當前用戶的滑動意圖。
*/
private void checkSlideState(int moveDistanceX, int moveDistanceY) {
if (isLeftLayoutVisible) {
if (!isSliding && Math.abs(moveDistanceX) >= touchSlop && moveDistanceX < 0) {
isSliding = true;
slideState = HIDE_MENU;
}
} else if (!isSliding && Math.abs(moveDistanceX) >= touchSlop && moveDistanceX > 0
&& Math.abs(moveDistanceY) < touchSlop) {
isSliding = true;
slideState = SHOW_MENU;
}
}
/**
* 在滑動過程中檢查左側菜單的邊界值,防止綁定布局滑出屏幕。
*/
private void checkSlideBorder() {
if (rightLayoutParams.rightMargin > leftEdge) {
rightLayoutParams.rightMargin = leftEdge;
} else if (rightLayoutParams.rightMargin < rightEdge) {
rightLayoutParams.rightMargin = rightEdge;
}
}
/**
* 判斷是否應該滾動將左側布局展示出來。
*/
private boolean shouldScrollToLeftLayout() {
return xUp - xDown > leftLayoutParams.width / 2 || getScrollVelocity() > SNAP_VELOCITY;
}
/**
* 判斷是否應該滾動將右側布局展示出來。
*/
private boolean shouldScrollToRightLayout() {
return xDown - xUp > leftLayoutParams.width / 2 || getScrollVelocity() > SNAP_VELOCITY;
}
private void createVelocityTracker(MotionEvent event) {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
}
/**
* 獲取手指在右側布局的監聽 View 上的滑動速度。
*/
private int getScrollVelocity() {
mVelocityTracker.computeCurrentVelocity(1000);
int velocity = (int) mVelocityTracker.getXVelocity();
return Math.abs(velocity);
}
private void recycleVelocityTracker() {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
/**
* 使用可以獲得焦點的控件在滑動的時候失去焦點。
*/
private void unFocusBindView() {
if (mBindView != null) {
mBindView.setPressed(false);
mBindView.setFocusable(false);
mBindView.setFocusableInTouchMode(false);
}
}
/**
* 保證此時讓左側布局不可見,3D 視圖可見,從而讓滑動過程中產生 3D 的效果。
*/
private void showImage3dView() {
if (image3dView.getVisibility() != View.VISIBLE) {
image3dView.setVisibility(View.VISIBLE);
}
if (leftLayout.getVisibility() != View.INVISIBLE) {
leftLayout.setVisibility(View.INVISIBLE);
}
}
class ScrollTask extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... speed) {
int rightMargin = rightLayoutParams.rightMargin;
// 根據傳入的速度來滾動界面,當滾動到達左邊界或右邊界時,跳出循環。
while (true) {
rightMargin = rightMargin + speed[0];
if (rightMargin < rightEdge) {
rightMargin = rightEdge;
break;
}
if (rightMargin > leftEdge) {
rightMargin = leftEdge;
break;
}
publishProgress(rightMargin);
// 為了要有滾動效果產生,每次循環使線程睡眠 5 毫秒
sleep(5);
}
if (speed[0] > 0) {
isLeftLayoutVisible = false;
} else {
isLeftLayoutVisible = true;
}
isSliding = false;
return rightMargin;
}
@Override
protected void onProgressUpdate(Integer... rightMargin) {
rightLayoutParams.rightMargin = rightMargin[0];
rightLayout.setLayoutParams(rightLayoutParams);
image3dViewParams = image3dView.getLayoutParams();
image3dViewParams.width = -rightLayoutParams.rightMargin;
image3dView.setLayoutParams(image3dViewParams);
showImage3dView();
unFocusBindView();
}
@Override
protected void onPostExecute(Integer rightMargin) {
rightLayoutParams.rightMargin = rightMargin;
rightLayout.setLayoutParams(rightLayoutParams);
image3dViewParams = image3dView.getLayoutParams();
image3dViewParams.width = -rightLayoutParams.rightMargin;
image3dView.setLayoutParams(image3dViewParams);
if (isLeftLayoutVisible) {
// 保證在滑動結束後左側布局可見,3D 視圖不可見
image3dView.setVisibility(View.INVISIBLE);
leftLayout.setVisibility(View.VISIBLE);
}
}
}
/**
* 使當前線程睡眠指定的毫秒數。
*/
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
把思路理一遍會清楚很多。
onLayout() 裡做一次性初始化:拿到左側布局、右側布局與 Image3dView,並把左側布局交給 Image3dView 作為拓印來源。注意 loadOnce 標誌位,這段初始化只做一次就夠了。
手指按在被綁定的 View 上拖動時進入 onTouch()。checkSlideState() 判斷用戶意圖是「拉出菜單」還是「收起菜單」,然後按拖動距離調整右側布局的 rightMargin,基礎的側滑效果就出來了。
重點在 onSlide():它同步修改 Image3dView 的寬度。寬度一變,View 必然重新走 onDraw(),我們寫的三維旋轉邏輯就在這一刻被執行,立體的推拉門錯覺由此產生。整個滑動過程中,真正的左側布局始終是 INVISIBLE,用戶看到的只有那張會轉的圖片。
手指離開屏幕後,shouldScrollToLeftLayout() / shouldScrollToRightLayout() 會結合拖動距離(超過菜單寬度一半)與滑動速度(超過 SNAP_VELOCITY)判斷用戶到底想幹嘛,然後 scrollToLeftLayout() 或 scrollToRightLayout() 啟動 ScrollTask 完成收尾滾動。等滾動徹底結束,onPostExecute() 才把真菜單換上來、把圖片藏起來——這時菜單裡的按鈕才真正可點。
打開或新建 activity_main.xml:
<com.example.slidinglayout3d.ThreeDSlidingLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/slidingLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="@+id/menu"
android:layout_width="270dip"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:background="#00ccff"
android:visibility="invisible" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="This is menu"
android:textColor="#000000"
android:textSize="28sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Test Button" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/content"
android:layout_width="320dip"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#e9e9e9"
android:orientation="vertical"
android:visibility="visible" >
<Button
android:id="@+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Menu" />
<ListView
android:id="@+id/contentList"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000" >
</ListView>
</LinearLayout>
<com.example.slidinglayout3d.Image3dView
android:id="@+id/image_3d_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:visibility="invisible" />
</com.example.slidinglayout3d.ThreeDSlidingLayout>
最外層是我們自定義的 ThreeDSlidingLayout,裡面掛著三個直接子布局:左側菜單(一個 TextView 加一個按鈕,初始 invisible)、右側主布局(一個按鈕加一個 ListView),以及負責在滑動期間頂包的 Image3dView。
public class MainActivity extends Activity {
/**
* 側滑布局對象。
*/
private ThreeDSlidingLayout slidingLayout;
/**
* menu 按鈕,點擊按鈕展示左側布局,再點擊一次隱藏左側布局。
*/
private Button menuButton;
private ListView contentListView;
private ArrayAdapter<String> contentListAdapter;
private String[] contentItems = { "Content Item 1", "Content Item 2", "Content Item 3",
"Content Item 4", "Content Item 5", "Content Item 6", "Content Item 7",
"Content Item 8", "Content Item 9", "Content Item 10", "Content Item 11",
"Content Item 12", "Content Item 13", "Content Item 14", "Content Item 15",
"Content Item 16" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slidingLayout = (ThreeDSlidingLayout) findViewById(R.id.slidingLayout);
menuButton = (Button) findViewById(R.id.menuButton);
contentListView = (ListView) findViewById(R.id.contentList);
contentListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
contentItems);
contentListView.setAdapter(contentListAdapter);
// 將監聽滑動事件綁定在 contentListView 上
slidingLayout.setScrollEvent(contentListView);
menuButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (slidingLayout.isLeftLayoutVisible()) {
slidingLayout.scrollToRightLayout();
} else {
slidingLayout.scrollToLeftLayout();
}
}
});
contentListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = contentItems[position];
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
});
}
}
Activity 這邊幾乎沒有新東西:setScrollEvent() 把 ListView 綁為觸發 View,於是拖動列表就能帶出菜單;菜單按鈕則提供了另一條捷徑。
至此全部編碼完成,跑起來就能看到效果:手指拖動時,菜單像一扇門那樣沿著左邊緣立體翻開;手勢結束後門「關上」,真正的菜單就位待命。
說到底,關鍵僅僅是對 Camera 的巧妙運用。同一套 Matrix 加 Camera 的組合拳,稍微換個角度和軸向,還能搆展出大量別的玩法——就看你敢不敢讓想象力先跑起來。
源碼下載,請點擊這裡
Android 編程:監聽 EditText 內容變化的方法
本文介紹如何監聽 EditText 中內容的變化,供大家參考。 我們常常需要實時監聽輸入框裡文字的變化,比如根據輸入內容動態顯示或隱藏某個按鈕。翻了很久發現 EditTe
Android 登入畫面教學:帳密欄位設計與三次錯誤後鎖定的實作
登入畫面是使用者進入 Facebook、微博這類服務前的第一道門。它要收集一組憑證,驗證通過就放行。聽起來平凡,但實作時有三個細節決定成品是否堪用:密碼欄有沒有遮好、錯誤
動手做「開發者頭條」App(五):為 RecyclerView 加上下拉刷新與上拉加載
一、前言 這一篇的目標很單純:把「下拉刷新、上拉加載更多」這套幾乎每個資訊類 App 都少不了的交互,正式接進我們的開發者頭條專案裡。 先看效果: 自定義列表手勢這種事
Android 登入畫面實作:帳密驗證與錯誤次數限制
幾乎每個需要使用者帳號的 App 都少不了一個登入畫面,無論是自家服務還是 Facebook、微博這類第三方平台。本章要說明如何打造一個登入介面,並處理最容易被忽略的兩件