继承ViewGroup类方式(循序渐进之第2步效果

———————–下面这个效果只是整个效果的第二步-(目前左右拖动图片+回弹效果)—一会继续更新博客————————-

配置文件

activity_main.xml(不解释,只有一个自定义控件)

[html]view plain

mScrollView.java

package com.example.mscrollview;import android.R.xml;import android.content.Context;import android.util.AttributeSet;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;public class mScrollView extends ViewGroup {//定义手势识别器private GestureDetector gestureDetector;//1、构造器public mScrollView(Context context, AttributeSet attrs) {super(context, attrs);initView(context);}/* * 2、得到孩子页面的位置和大小 */@Overrideprotected void onLayout(boolean changed, int l, int t, int r, int b) {for (int i = 0; i < getChildCount(); i++) {//根据id得到孩子View childView = getChildAt(i);//布局每个页面的位置childView.layout(i*getWidth(), 0, getWidth()+getWidth()*i, getHeight());}}/* * 初始化view */private void initView(Context context) {//手势识别实例化gestureDetector = new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){//手指拖动调用该方法,e1代表按下,e2代表离开事件@Overridepublic boolean onScroll(MotionEvent e1, MotionEvent e2,float distanceX, float distanceY) {//x轴y轴移动的距离scrollBy((int) distanceX, 0);//事件处理完毕return true;//scrollTo(x,y)要移动到的坐标上}});}/** * 接收事件onScroll *///记录起始坐标private float startX;//记录目前页面的索引位置private int currentIndex;@Overridepublic boolean onTouchEvent(MotionEvent event) {super.onTouchEvent(event);//执行父类方法,事件不会被拦截//接受事件gestureDetector.onTouchEvent(event);switch (event.getAction()) {//这个案例事件涉及到三种,按下、移动、离开case MotionEvent.ACTION_DOWN://只要一按下就记录起始坐标startX = event.getX();break;case MotionEvent.ACTION_MOVE:break;case MotionEvent.ACTION_UP://手指离开,记录新坐标float endX = event.getX();//计算偏移量if (endX-startX>getWidth()/2) {//上一个页面currentIndex –;}else if(startX – endX >getWidth()/2){//显示下一个页面currentIndex ++;}moveTo(currentIndex);break;default:break;}return true;}/* * 根据当前页面索引,移动到对应的位置 */private void moveTo(int ScrolledIndex) {//屏蔽非法值如果移动到的页面缩影小于0就直接定位到第一张if (ScrolledIndex<0) {ScrolledIndex = 0;}//如果移动到的页码大于最后一张页面的索引,,就定位到最后一张if (ScrolledIndex > getChildCount()-1) {ScrolledIndex = getChildCount()-1;}//将新的页面索引赋值给目前的页面索引值currentIndex = ScrolledIndex;//定位到某个坐标scrollTo(currentIndex*getWidth(), 0);}}

MainActivity.java(步骤都在注释里,简单明了,就是得到图片资源,得到自定义控件,将图片放到自定义控件里,因为自定义控件是继承Viewgroup,是一个组合,需要添加东西,ok? ok!)

[java]view plain

packagecom.example.mscrollview;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.ImageView;//1、图片资源R.drawable.a3,R.drawable.a5,R.drawable.a6};//2、定义自定义控件privatemScrollViewmsv;@Overridesuper.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//创建自定义控件对象msv=(mScrollView)findViewById(R.id.msv);//循环遍历6张图片,依次为图片对象添加背景图片,然后加入到msv自定义控件中iv.setBackgroundResource(ids[i]);//3、添加子页面msv.addView(iv);}}}

一旦有了意志,脚步也会轻松起来。

继承ViewGroup类方式(循序渐进之第2步效果

相关文章:

你感兴趣的文章:

标签云: