Android自定义控件ScrollView实现上下滑动功能
本文实例为大家分享了AndroidScrollView实现上下滑动功能的具体代码,供大家参考,具体内容如下
packagecom.example.zhuang;
importandroid.content.Context;
importandroid.util.AttributeSet;
importandroid.util.DisplayMetrics;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.view.WindowManager;
importandroid.widget.Scroller;
publicclassMyScrollViewextendsViewGroup{
privateintmScreeHeight;//屏幕高度
privateScrollermScroller;
privateintmLastY;
privateintmStart;
privateintmEnd;
privateContextcontext;
publicMyScrollView(Contextcontext){
super(context);
initView(context);
}
publicMyScrollView(Contextcontext,AttributeSetattrs){
super(context,attrs);
initView(context);
}
publicMyScrollView(Contextcontext,AttributeSetattrs,
intdefStyleAttr){
super(context,attrs,defStyleAttr);
initView(context);
}
privatevoidinitView(Contextcontext){
WindowManagerwm=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
//DisplayMetrics类提供了一种关于显示的通用信息,如显示大小,分辨率和字体。
DisplayMetricsdm=newDisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
mScreeHeight=dm.heightPixels;//高度(像素)
mScroller=newScroller(context);
}
//继承ViewGroup必须要实现的方法
@Override
protectedvoidonLayout(booleanchanged,intl,intt,intr,intb){
intchildCount=getChildCount();//获取子view的个数
//设置ViewGroup的高度
MarginLayoutParamsmlp=(MarginLayoutParams)getLayoutParams();
mlp.height=mScreeHeight*childCount;
setLayoutParams(mlp);
for(inti=0;igetHeight()-mScreeHeight){
dy=0;
}
scrollBy(0,dy);//移动
mLastY=y;
break;
caseMotionEvent.ACTION_UP:
intdScrollY=checkAlignment();//整体移动的距离
if(dScrollY>0){
if(dScrollY0)?true:false;
intlastPrev=mEnd%mScreeHeight;
intlastNext=mScreeHeight-lastPrev;
if(isUp){
returnlastPrev;//向上
}else
return-lastNext;
}
@Override
publicvoidcomputeScroll(){
super.computeScroll();
if(mScroller.computeScrollOffset()){//返回true,表示还未移动完
scrollTo(0,mScroller.getCurrY());//移到当前位置
postInvalidate();
//invalidate()是用来刷新View的,必须是在UI线程中进行工作。
//postInvalidate()可以在非UI线程调用
}
}
}
知识点:
1、获取屏幕参数代码:
DisplayMetricsmetric=newDisplayMetrics(); //API17之后使用,获取的像素宽高包含虚拟键所占空间,在API17之前通过反射获取 context.getWindowManager().getDefaultDisplay().getRealMetrics(metric); //获取的像素宽高不包含虚拟键所占空间 //context.getWindowManager().getDefaultDisplay().getMetrics(metric); intwidth=metric.widthPixels;//宽度(像素) intheight=metric.heightPixels;//高度(像素) floatdensity=metric.density;//dp缩放因子 intdensityDpi=metric.densityDpi;//广义密度 floatxdpi=metric.xdpi;//x轴方向的真实密度 floatydpi=metric.ydpi;//y轴方向的真实密度
屏幕高度值包含了状态栏的像素,非沉浸模式下真实的Activity高度需要减去状态栏的高度。获取状态栏高度代码:
privateintgetStatusBarHeight(){
Rectrect=newRect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
returnrect.top;
}
屏幕参数Width和Height的值和屏幕方向有关,另外4个值和屏幕方向无关。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。