天天看点

Android 视图切换效果

 我们先来看看效果图:

Android 视图切换效果

       上述截图,是手指拖动的效果,如果拖动过屏幕中点,松手后就会自动移动到第二屏。另外,如果使用轻扫手势,也可以自动移动下一屏。

        android中的view有两个子类,widget和viewgroup,widget是可见的窗口组件,比如按钮,viewgroup就是布局,viewgroup已经提供了多个布局子类,比如linearlayout等。

       本例中实现了自己的viewgroup子类。通过覆盖onlayout方法实现对子视图的横向排列布局:

java代码:

package eoe. result;

@override

protected void onlayout(boolean changed, int left, int top, int right,

int bottom) {

log.d(tag, ">>left: " + left + " top: " + top + " right: " + right

+ " bottom:" + bottom);

/**

* 设置布局,将子视图顺序横屏排列

*/

for (int i = 0; i < getchildcount(); i++) {

view child = getchildat(i);

child.setvisibility(view.visible);

child.measure(right – left, bottom – top);

child.layout(0 + i * getwidth(), 0, getwidth() + i * getwidth(),

getheight());

复制代码

        通过覆盖computescroll方法,计算移动屏幕的位移和重新绘制屏幕:

public void computescroll() {

if (scroller.computescrolloffset()) {

scrollto(scroller.getcurrx(), 0);

postinvalidate();

}

        编写了一个名为scrolltoscreen的方法,用于根据指定屏幕号切换到该屏幕:

* 切换到指定屏

*

* @param whichscreen

public void scrolltoscreen(int whichscreen) {

if (getfocusedchild() != null && whichscreen != currentscreenindex

&& getfocusedchild() == getchildat(currentscreenindex)) {

getfocusedchild().clearfocus();

final int delta = whichscreen * getwidth() – getscrollx();

scroller.startscroll(getscrollx(), 0, delta, 0, math.abs(delta) * 2);

invalidate();

currentscreenindex = whichscreen;

        snaptodestination方法,是处理当屏幕拖动到一个位置松手后的处理:

* 根据当前x坐标位置确定切换到第几屏

private void snaptodestination() {

scrolltoscreen((getscrollx() + (getwidth() / 2)) / getwidth());

       然后说说手势事件的处理。eric的实现,全部使用ontouch事件处理,这样代码不够简明。因为需要记录很多组合手势的历史数据,这样就必须有一些状态位,一些坐标数值。

       我用gesturedetector的手势处理事件简化了这方面的处理,只在手势抬起(up)事件处理中在outouchevent方法中做了处理。

继续阅读