ViewDragHelper和SwipeBackLayout的若干笔记

524 查看

SwipeBackLayout

SwipeBackLayout是一个好用的第三方库(特别是README,因为是中文T.T),代码也很简单,主要是以下几个文件:

  • Utils.java

  • SwipeBackLayout.java

  • ViewDragHelper.java

以及默认继承自FragmentActivitySwipeBackActivity

SwipeBackLayout的使用依赖android-support-4.jar,但是其使用了较高版本中的ViewDragHelper官方类,不过方法是直接引用了一个文件。

AppCompatActivity的使用

新时代中,经历了ActionBarActivity之后,迎来了新的AppCompatActivity,对于继承自FragmentActivitySwipeBackActivity自然是不够用,不过好在SwipeBackActivity结构简单,只需要模仿代码中SwipeBackActivity的写法,继承自AppCompatActivity即可。

public class AppCompatSwipeBackActivity extends AppCompatActivity implements SwipeBackActivityBase {
    private SwipeBackActivityHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHelper = new SwipeBackActivityHelper(this);
        mHelper.onActivityCreate();;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mHelper.onPostCreate();
    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null &&  mHelper != null) {
            return mHelper.findViewById(id);
        }
        return v;
    }

    @Override
    public SwipeBackLayout getSwipeBackLayout() {
        return mHelper.getSwipeBackLayout();
    }

    @Override
    public void setSwipeBackEnable(boolean enable) {
        getSwipeBackLayout().setEnableGesture(enable);
    }

    @Override
    public void scrollToFinishActivity() {
        Utils.convertActivityToTranslucent(this);
        getSwipeBackLayout().scrollToFinishActivity();
    }
}

使用SwipeBackLayout库的Activity需要在Theme中设置

<item name="android:windowIsTranslucent">true</item>

即可。

ViewDragHelper的使用

ViewDragHelper特性

  • ViewDragHelper.Callback连接了ViewDragHelper和其需要处理的View(其实必须是ViewGroup

  • ViewDragHelper必须通过工程静态方法ViewDragHelper.create创建

  • 可以指定拖动方向

  • 可以检测是否触及边缘

  • ViewDragHelper不直接处理拖动的View,而是通过callback使其容器对View进行操作

  • ViewDragHelper本质是分析OnInterceptTouchEventOnTouchEventMotionEvent参数,从而改变容器中被拖动的子View位置

ViewDragHelper是在自定义Layout中而不是在一个任意的Layout中使用。

使用方法