如何在Android中执行拖动幻灯片视图

时间:2014-03-21 18:10:53

标签: android android-layout android-listview

我需要能够在列出第一个listview下面的另一个列表视图的同时将列表视图拖动到左侧和视图之外。我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

您可以使用OnTouchListener并在ACTION_MOVE上调整大小或移动某些视图。记得调用setClickable(true)以确保调用ACTION_MOVE。

下面是滑动视图的示例:

布局:

<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <LinearLayout
            android:id="@+id/background_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        (more content)

    </LinearLayout>
    <LinearLayout
            android:id="@+id/sliding_view"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <View
                android:id="@+id/draggable_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        (more content)

    </LinearLayout>

</RelativeLayout>

设置视图:

View slidingView = ...
View draggableView = ... //placed inside slidingView, this is where you touch and drag
draggableView.setOnTouchListener(new TouchListener(slidingView));
draggableView.setClickable(true); //if not set, only ACTION_DOWN gets called, ACTION_MOVE doesn't

监听器:

private class TouchListener implements View.OnTouchListener{

        View slidingView;

        int initHeight;
        float initPos;
        ViewGroup.LayoutParams params;

        private TouchListener(View slidingView) {
            this.slidingView = slidingView;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(params == null){
                params = slidingView.getLayoutParams();
            }

            switch (event.getActionMasked()){
                case ACTION_DOWN: //get initial state
                    initHeight = slidingView.getHeight();
                    initPos = event.getRawY();
                    break;
                case ACTION_MOVE: //do the sliding
                    float dPos = initPos - event.getRawY();
                    params.height = Math.round(initHeight + dPos);
                    slidingView.requestLayout(); //refresh layout
                    break;
            }

            return false;
        }
    }

注意:如果ACTION_MOVE仍然没有被调用,除了setClickable之外,还可以尝试调用setFocusable。我的&#34;可拖动视图&#34;我不需要这样做。虽然是TextView。