Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義布局實現雙向側滑菜單(下篇)

編輯:關於 Android 程式設計

上一節我們已經說明了側滑菜單的實現原理,並完成了單側菜單。這一節我們來完善專案,實現雙向側滑菜單。原理若不清楚可回看上節,這裡直接上程式碼。

 /**
 * 這個類和 SlidingLayout 作用一樣,只是沒有實現觸摸監聽事件,直接在 121 行設置實現了
 */
public class SlidingLayout1 extends LinearLayout {
    /** 滾動顯示和隱藏左側布局時,手指滑動需要達到的速度。 */
    public static final int SNAP_VELOCITY = 200;
    /** 屏幕寬度值。 */
    private int screenWidth;
    /** 左側布局最多可以滑動到的左邊緣。值由左側布局的寬度來定。 */
    private int leftEdge;
    /** 左側布局最多可以滑動到的右邊緣。值恆為 0。 */
    private int rightEdge = 0;
    /** 左側布局完全顯示時,留給右側布局的寬度值。 */
    private int leftLayoutPadding = 80;
    /** 記錄手指按下時的橫坐標。 */
    private float xDown;
    /** 記錄手指移動時的橫坐標。 */
    private float xMove;
    /** 記錄手機抬起時的橫坐標。 */
    private float xUp;
    /** 左側布局當前是顯示還是隱藏。 */
    private boolean isLeftLayoutVisible;
    /** 左側布局對象。 */
    private View leftLayout;
    /** 右側布局對象。 */
    private View rightLayout;
    /** 用於監聽側滑事件的 View。 */
    private View mBindView;
    /** 左側布局的參數。 */
    private MarginLayoutParams leftLayoutParams;
    /** 右側布局的參數。 */
    private MarginLayoutParams rightLayoutParams;
    /** 用於計算手指滑動的速度。 */
    private VelocityTracker mVelocityTracker;
    public SlidingLayout1(Context context, AttributeSet attrs) {
        super(context, attrs);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        screenWidth = metrics.widthPixels;
    }
    /** 綁定監聽側滑事件的 View。 */
    public void setScrollEvent(View bindView) {
        mBindView = bindView;
        mBindView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                createVelocityTracker(event);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        xDown = event.getRawX();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        xMove = event.getRawX();
                        int distanceX = (int) (xMove - xDown);
                        if (isLeftLayoutVisible) {
                            leftLayoutParams.leftMargin = distanceX;
                        } else {
                            leftLayoutParams.leftMargin = leftEdge + distanceX;
                        }
                        if (leftLayoutParams.leftMargin < leftEdge) {
                            leftLayoutParams.leftMargin = leftEdge;
                        } else if (leftLayoutParams.leftMargin > rightEdge) {
                            leftLayoutParams.leftMargin = rightEdge;
                        }
                        leftLayout.setLayoutParams(leftLayoutParams);
                        break;
                    case MotionEvent.ACTION_UP:
                        xUp = event.getRawX();
                        if (wantToShowLeftLayout()) {
                            if (shouldScrollToLeftLayout()) {
                                scrollToLeftLayout();
                            } else {
                                scrollToRightLayout();
                            }
                        } else if (wantToShowRightLayout()) {
                            if (shouldScrollToContent()) {
                                scrollToRightLayout();
                            } else {
                                scrollToLeftLayout();
                            }
                        }
                        recycleVelocityTracker();
                        break;
                }
                return isBindBasicLayout();
            }
        });
    }
    /** 將屏幕滾動到左側布局界面,滾動速度設定為 30。 */
    public void scrollToLeftLayout() {
        new ScrollTask().execute(30);
    }
    /** 將屏幕滾動到右側布局界面,滾動速度設定為 -30。 */
    public void scrollToRightLayout() {
        new ScrollTask().execute(-30);
    }
    /** 左側布局是否完全顯示出來。 */
    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) {
            leftLayout = getChildAt(0);
            leftLayoutParams = (MarginLayoutParams) leftLayout.getLayoutParams();
            leftLayoutParams.width = screenWidth - leftLayoutPadding;
            leftEdge = -leftLayoutParams.width;
            leftLayoutParams.leftMargin = leftEdge;
            leftLayout.setLayoutParams(leftLayoutParams);
            rightLayout = getChildAt(1);
            rightLayoutParams = (MarginLayoutParams) rightLayout.getLayoutParams();
            rightLayoutParams.width = screenWidth;
            rightLayout.setLayoutParams(rightLayoutParams);
        }
    }
    /** 判斷當前手勢的意圖是不是想顯示右側布局。 */
    private boolean wantToShowRightLayout() {
        return xUp - xDown < 0 && isLeftLayoutVisible;
    }
    /** 判斷當前手勢的意圖是不是想顯示左側布局。 */
    private boolean wantToShowLeftLayout() {
        return xUp - xDown > 0 && !isLeftLayoutVisible;
    }
    /** 判斷是否應該滾動將左側布局展示出來。 */
    private boolean shouldScrollToLeftLayout() {
        return xUp - xDown > screenWidth / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }
    /** 判斷是否應該滾動將右側布局展示出來。 */
    private boolean shouldScrollToContent() {
        return xDown - xUp + leftLayoutPadding > screenWidth / 2 || getScrollVelocity() > SNAP_VELOCITY;
    }
    /** 判斷綁定滑動事件的 View 是不是一個基礎 layout。 */
    private boolean isBindBasicLayout() {
        if (mBindView == null) {
            return false;
        }
        String viewName = mBindView.getClass().getName();
        return viewName.equals(LinearLayout.class.getName())
            || viewName.equals(RelativeLayout.class.getName())
            || viewName.equals(FrameLayout.class.getName())
            || viewName.equals(TableLayout.class.getName());
    }
    /** 創建 VelocityTracker 對象。 */
    private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }
    /** 獲取手指滑動速度。 */
    private int getScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getXVelocity();
        return Math.abs(velocity);
    }
    /** 回收 VelocityTracker 對象。 */
    private void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }
    class ScrollTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected Integer doInBackground(Integer... speed) {
            int leftMargin = leftLayoutParams.leftMargin;
            while (true) {
                leftMargin = leftMargin + speed[0];
                if (leftMargin > rightEdge) {
                    leftMargin = rightEdge;
                    break;
                }
                if (leftMargin < leftEdge) {
                    leftMargin = leftEdge;
                    break;
                }
                publishProgress(leftMargin);
                // 每次循環使線程睡眠 20 毫秒,肉眼才能看到滾動動畫
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (speed[0] > 0) {
                isLeftLayoutVisible = true;
            } else {
                isLeftLayoutVisible = false;
            }
            return leftMargin;
        }
        @Override
        protected void onProgressUpdate(Integer... leftMargin) {
            leftLayoutParams.leftMargin = leftMargin[0];
            leftLayout.setLayoutParams(leftLayoutParams);
        }
        @Override
        protected void onPostExecute(Integer leftMargin) {
            leftLayoutParams.leftMargin = leftMargin;
            leftLayout.setLayoutParams(leftLayoutParams);
        }
    }
}

首先在 onLayout() 方法中分別取得左側菜單、右側菜單和內容布局的參數,並把內容布局的寬度重定義成屏幕寬度,這樣就能保證內容布局既能覆蓋住下面的菜單布局,還能偏移出屏幕。接著在 onTouch() 中監聽觸屏事件,判斷用戶手勢的意圖。這裡事先定義了幾種滑動狀態:DO_NOTHING 表示沒有滑動,SHOW_LEFT_MENU 表示想滑出左側菜單,SHOW_RIGHT_MENU 表示想滑出右側菜單,HIDE_LEFT_MENU 與 HIDE_RIGHT_MENU 分別表示隱藏左、右側菜單。在 checkSlideState() 中判斷用戶想進行哪一種滑動並給 slideState 賦值,再據此決定如何偏移內容布局。當用戶手指離開屏幕時,會根據當前滑動距離決定後續滾動方向,透過 ScrollTask 完成完整的滑動過程。滑動過程中,內容布局上的事件會被屏蔽,主要透過一系列 return 操作實現。

在布局中引用

 <com.example.demo.view.SlidingLayout2
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/slidingLayout_fragment_double"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <RelativeLayout
        android:layout_width="280dip"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:background="#00ccff"
        android:visibility="invisible" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="This is left menu"
            android:textColor="#000000"
            android:textSize="28sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="280dip"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:background="#00ffcc"
        android:visibility="invisible" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="This is right menu"
            android:textColor="#000000"
            android:textSize="28sp" />
    </RelativeLayout>
    <LinearLayout
        android:id="@+id/content"
        android:layout_width="320dip"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="#e9e9e9" >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
            <Button
                android:id="@+id/show_left_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="show left" />
            <Button
                android:id="@+id/show_right_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:text="show right" />
            <ListView
                android:id="@+id/contentList"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:scrollbars="none"
                android:cacheColorHint="#00000000" >
            </ListView>
        </RelativeLayout>
    </LinearLayout>
</com.example.demo.view.SlidingLayout2>

這裡使用了自定義的 SlidingLayout2 作為根布局,然後依次加入三個子布局分別作為左側菜單、右側菜單和內容布局。左側菜單與右側菜單中都只放入一個 TextView 顯示文字,內容布局中放入一個 ListView。注意要讓左側菜單和父布局左邊緣對齊,右側菜單和父布局右邊緣對齊。

用法參照上篇,我也寫在了一個 Fragment 中:

 public class DoubleMenu extends Fragment {
    /** 雙向滑動菜單布局 */
    private SlidingLayout2 doubleSldingLayout;
    /** 在內容布局上顯示的 ListView */
    private ListView contentList;
    /** ListView 的適配器 */
    private ArrayAdapter<String> contentListAdapter;
    /** 用於填充 contentListAdapter 的數據源。 */
    private List<String> dataList;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_double, container, false);
        doubleSldingLayout = (SlidingLayout2) view.findViewById(R.id.slidingLayout_fragment_double);
        Button showLeftButton = (Button) view.findViewById(R.id.show_left_button);
        Button showRightButton = (Button) view.findViewById(R.id.show_right_button);
        contentList = (ListView) view.findViewById(R.id.contentList);
        dataList = new ArrayList<>();
        for (int i = 0; i < 15; i++)
            dataList.add("Item " + i);
        contentListAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, dataList);
        contentList.setAdapter(contentListAdapter);
        doubleSldingLayout.setScrollEvent(contentList);
        showLeftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (doubleSldingLayout.isLeftLayoutVisible()) {
                    doubleSldingLayout.scrollToContentFromLeftMenu();
                } else {
                    doubleSldingLayout.initShowLeftState();
                    doubleSldingLayout.scrollToLeftMenu();
                }
            }
        });
        showRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (doubleSldingLayout.isRightLayoutVisible()) {
                    doubleSldingLayout.scrollToContentFromRightMenu();
                } else {
                    doubleSldingLayout.initShowRightState();
                    doubleSldingLayout.scrollToRightMenu();
                }
            }
        });
        return view;
    }
}

看下效果:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved