先上效果图:
实现“左右滑屏”核心类是Scroller,将View中的内容左右滚动从而实现滑屏效果。关键方法有:
scroller.scrollTo(x,y):
直接将View中的内容滚动到指定的(x,y)位置。
scroller.scrollTo(dx,dy):
直接将View中的内容滚动到相对当前状态的(dx,dy)位置。本例中用于实现手指拖拉移动View的效果。
scroller.startScroll(nowX, nowY, moveX, moveY, duration):
在duration的时间内完成move的位移。配合重写View.computeScroll()不断刷新界面从而实现滑屏动画。
如果当前点击拖拉的组件是按钮等自身可处理手势动作的组件,则重写ViewGroup.onInterceptTouchEvent(MotionEvent)可拦截此事件并将此事件传递至onTouchEvent(MotionEvent)进行处理。从而对如按钮等即可点击亦可拖拉。
左右滑屏的指示器位置为SlidingIndicator。在fadeOut()方法中为本组件的动画设置了延时,体验上更亲近:
animFadeout.setStartTime(AnimationUtils.currentAnimationTimeMillis() + fadeDelay);
setAnimation(animFadeout);
本文内容归优快云博客博主Sodino 所有
转载请注明出处:http://blog.youkuaiyun.com/sodino/article/details/7211049
ActSlidingContainer.java
package lab.sodino.sliding;
import lab.sodino.sliding.SlidingContainer.OnSlidingListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ActSlidingContainer extends Activity implements OnClickListener, OnSlidingListener {
private SlidingContainer slidingContainer;
private SlidingIndicator slidingIndicator;
private Button btnLeft, btnRight, btnMid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnLeft = (Button) findViewById(R.id.left);
btnLeft.setOnClickListener(this);
btnRight = (Button) findViewById(R.id.right);
btnRight.setOnClickListener(this);
btnMid = (Button) findViewById(R.id.mid);
btnMid.setOnClickListener(this);
slidingContainer = (SlidingContainer) findViewById(R.id.slidingContainer);
slidingContainer.setOnSlidingListener(this);
slidingIndicator = (SlidingIndicator) findViewById(R.id.slidingIndicator);
slidingIndicator.setPageAmount(slidingContainer.getChildCount());
}
@Override
public void onClick(View v) {
if (v == btnLeft) {
slidingContainer.scroll2page(slidingContainer.getCurrentPage() - 1);
} else if (v == btnRight) {
slidingContainer.scroll2page(slidingContainer.getCurrentPage() + 1);
} else if (v == btnMid) {
slidingContainer.scroll2page(slidingContainer.getChildCount() >> 1);
}
}
@Override
public void onSliding(int scrollX) {
float scale = (float) (slidingContainer.getPageWidth() * slidingContainer.getChildCount())
/ (float) slidingIndicator.getWidth();
slidingIndicator.setPosition((int) (scrollX / scale));
}
@Override
public void onSlidingEnd(int pageIdx, int scrollX) {
slidingIndicator.setCurrentPage(pageIdx);
}
}
<