`

使用ViewDragHelper实现的DragLayout开门效果

阅读更多
先看一下图,有个直观的了解,向下拖动handle就“开门了”:



此DragLayout继承自LinearLayout,这样使得布局变的简单。
我把最顶部的View叫做HeadView,中间的叫“把手”HandleView,底部的叫ContentView,姑且这样叫着。
只有把手可以拖动,下面的ContentView不可以!
只要给DragLayout设置一个background,就会产生一个渐变显示背后布局的效果。
由于DragLayout继承自LinearLayout,所以背后的布局不属于DragLayout的范畴,
DragLayout只有三部分组成(HeadView,HandleView,ContentView)。
这样就造成了背后的布局不能响应手势事件(点击,拖动等),为什么?(该问题已经解决,见帖子最后部分)
因为使用ViewDragHelper需要重写onTouchEvent方法:
@Override
	public boolean onTouchEvent(MotionEvent ev) {
		mDragHelper.processTouchEvent(ev);
		return true;
	}

此方法必须返回true,消费掉了手势事件,所以背后的View就不会响应事件啦。
有无好办法让背后的View也响应事件???
我初步的构想:把背后的View也纳入到DragLayout布局中去,这样DragLayout就不应该继承LinearLayout,最好继承ViewGroup,这样布局的灵活度更高,当然也更繁碎,需要重写onLayout和onMeasure等方法。但至少可以解决背后View不能响应点击事件的问题!(我想应该是这样)

目前只能将就一下,给个初步的DragLayout实现源码:
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 
 * @author pythoner
 * @since 2015-10-23
 *
 */
public class DragLayout extends LinearLayout {

	private ViewDragHelper mDragHelper;
	private View headView,handleView,contentView;//三个控件
	private int headViewHeight,handleViewHeight,contentViewHeight;//三个控件高度
	private boolean isOpen=false;
	public DragLayout(Context context) {
		this(context, null);
	}

	public DragLayout(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public DragLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mDragHelper = ViewDragHelper.create(this, 1.0f, new DragHelperCallback());
		setOrientation(LinearLayout.VERTICAL);
	}

	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		headView = findViewById(R.id.headView);
		handleView = findViewById(R.id.handleView);
		contentView = findViewById(R.id.contentView);
	}
	
	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		headViewHeight = headView.getMeasuredHeight();
		handleViewHeight = handleView.getMeasuredHeight();
		contentViewHeight = contentView.getMeasuredHeight();
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		final int action = MotionEventCompat.getActionMasked(ev);
		if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
			mDragHelper.cancel();
			return false;
		}
		return mDragHelper.shouldInterceptTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		mDragHelper.processTouchEvent(ev);
		return true;
	}

	@Override
	public void computeScroll() {
		super.computeScroll();
		if (mDragHelper.continueSettling(true)) {
			ViewCompat.postInvalidateOnAnimation(this);
		}
	}

	class DragHelperCallback extends ViewDragHelper.Callback {

		@Override
		public boolean tryCaptureView(View child, int pointerId) {
			return child == handleView;//只有把手可以拖拽
		}

		@Override
		public int clampViewPositionVertical(View child, int top, int dy) {
			// final int topBound = getPaddingTop();
			//只在Y方向上可以拖动,且拖动范围介于HeadView之下
			final int topBound = getPaddingTop() + headViewHeight;
			final int bottomBound = getHeight() - handleViewHeight;
			final int newTop = Math.min(Math.max(top, topBound), bottomBound);
			return newTop;
		}

		@Override
		public void onViewReleased(View releasedChild, float xvel, float yvel) {
			super.onViewReleased(releasedChild, xvel, yvel);
			//向下快速滑动或者向下滑动超过一半的ContentView时(慢速拖动的情况)
			if(yvel>0||releasedChild.getY()>headViewHeight+contentViewHeight/2){
				mDragHelper.settleCapturedViewAt((int) handleView.getX(), getHeight() - handleViewHeight);
				if(onScrollListener!=null){
					onScrollListener.onOpen(releasedChild);
				}
				isOpen=true;
			}else{
				mDragHelper.settleCapturedViewAt((int) handleView.getX(), headViewHeight);
				if(onScrollListener!=null){
					onScrollListener.onClose(releasedChild);
				}
				isOpen=false;
			}
			// 需要invalidate()以及结合computeScroll方法一起
			invalidate();
		}

		@Override
		public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
			super.onViewPositionChanged(changedView, left, top, dx, dy);
			headView.setY(headView.getY() - dy);
//			 contentView.setY(contentView.getY()+dy);//此处不能使用setY(),否则拖动不上去了,why?所以采用了变通的layout()改变位置
			contentView.layout(contentView.getLeft(), (int) (contentView.getY() + dy), contentView.getRight(),
					contentView.getBottom());
			float fraction=(top-headViewHeight)*1.00f/contentViewHeight;//滑动位移比率
			getBackground().setAlpha((int)(255*(1-fraction)));//背景根据滑动比率产生渐变效果
			if(onScrollListener!=null){
				onScrollListener.onScroll(changedView,fraction);
			}
		}
		
	}

	public boolean isOpen(){
		return isOpen;
	}
	
	private OnScrollListener onScrollListener;
	
	public void setOnScrollListener(OnScrollListener onScrollListener) {
		this.onScrollListener = onScrollListener;
	}

	interface OnScrollListener{
		void onScroll(View view,float fraction);
		void onOpen(View view);
		void onClose(View view);
	}
}



测试代码:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		DragLayout dragLayout=(DragLayout)findViewById(R.id.dragLayout);
		dragLayout.setOnScrollListener(new DragLayout.OnScrollListener() {
			
			@Override
			public void onScroll(View view, float fraction) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onOpen(View view) {
				// TODO Auto-generated method stub
				Log.i("tag", "============onOpen============");
			}
			
			@Override
			public void onClose(View view) {
				// TODO Auto-generated method stub
				Log.i("tag", "============onClose============");
			}
		});
		
		TextView tv_head=(TextView)findViewById(R.id.tv_head);
		TextView tv_content=(TextView)findViewById(R.id.tv_content);
		tv_head.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "tv_head clicked", Toast.LENGTH_SHORT).show();
			}
		});
		tv_content.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, "tv_content clicked", Toast.LENGTH_SHORT).show();
			}
		});
		
	}
}


测试布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:background="@android:color/holo_orange_dark"
    >

    <com.example.viewdraghelper.DragLayout
        android:id="@+id/dragLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/background_dark" >

        <FrameLayout
            android:id="@+id/headView"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@android:color/holo_blue_bright" >

            <TextView
                android:id="@+id/tv_head"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="head"
                android:textSize="48sp" />
        </FrameLayout>

        <TextView
            android:id="@+id/handleView"
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@android:color/holo_blue_dark"
            android:gravity="center"
            android:text="handle" />

        <FrameLayout
            android:id="@+id/contentView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_bright"
            android:focusable="false"
            android:focusableInTouchMode="false" >

            <TextView
                android:id="@+id/tv_content"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="content"
                android:textSize="48sp" />
        </FrameLayout>
    </com.example.viewdraghelper.DragLayout>

</FrameLayout>


整体的项目代码我不提供,有这三个就够了我想。


突然发现
解决背后的布局不能响应手势事件的问题很容易解决
只需要使用boolean isViewUnder = mDragHelper.isViewUnder(handleView, (int) x, (int) y);
判断一下就可以了
修改onTouchEvent()如下:
@Override
	public boolean onTouchEvent(MotionEvent ev) {
		try {
			mDragHelper.processTouchEvent(ev);
		} catch (Exception e) {
			// TODO: handle exception
		}
		final float x = ev.getX();  
	    final float y = ev.getY();
		boolean isViewUnder = mDragHelper.isViewUnder(handleView, (int) x, (int) y); 
		return isViewUnder;
	}

原来很简单的,之前还不知道此方法。

ViewDragHelper.CallBack中每个方法的用法
http://m.blog.csdn.net/blog/coder_nice/44678153


一个可以下滑显示出一个面板的Toolbar。这个library受Drawerlayout的启发,但有别于Drawerlayout显示左右抽屉,这个library会提供下拉toolbar显示一个面板的功能
http://www.jcodecraeer.com/a/opensource/2015/1204/3750.html
  • 大小: 74.5 KB
分享到:
评论

相关推荐

    win7修复本地系统工具

    win7修复本地系统工具

    《自动化专业英语》04-Automatic-Detection-Block(自动检测模块).ppt

    《自动化专业英语》04-Automatic-Detection-Block(自动检测模块).ppt

    《计算机专业英语》chapter12-Intelligent-Transportation.ppt

    《计算机专业英语》chapter12-Intelligent-Transportation.ppt

    西门子S7-1200博图平台下3轴伺服螺丝机程序解析与应用

    内容概要:本文详细介绍了基于西门子S7-1200博图平台的3轴伺服螺丝机程序。该程序使用SCL语言编写,结合KTP700组态和TIA V14及以上版本,实现了对X、Y、Z三个轴的精密控制。文章首先概述了程序的整体架构,强调了其在自动化控制领域的高参考价值。接着深入探讨了关键代码片段,如轴初始化、运动控制以及主程序的设计思路。此外,还展示了如何通过KTP700组态实现人机交互,并分享了一些实用的操作技巧和技术细节,如状态机设计、HMI交互、异常处理等。 适用人群:从事自动化控制系统开发的技术人员,尤其是对西门子PLC编程感兴趣的工程师。 使用场景及目标:适用于希望深入了解西门子S7-1200博图平台及其SCL语言编程特点的学习者;旨在帮助读者掌握3轴伺服系统的具体实现方法,提高实际项目中的编程能力。 其他说明:文中提供的代码示例和设计理念不仅有助于理解和学习,还能直接应用于类似的实际工程项目中。

    MATLAB仿真:非线性滤波器在水下长基线定位(LBL)系统的应用与比较

    内容概要:本文详细探讨了五种非线性滤波器(卡尔曼滤波(KF)、扩展卡尔曼滤波(EKF)、无迹卡尔曼滤波(UKF)、粒子滤波(PF)和变维卡尔曼滤波(VDKF))在水下长基线定位(LBL)系统中的应用。通过对每种滤波器的具体实现进行MATLAB代码展示,分析了它们在不同条件下的优缺点。例如,KF适用于线性系统但在非线性环境中失效;EKF通过雅可比矩阵线性化处理非线性问题,但在剧烈机动时表现不佳;UKF利用sigma点处理非线性,精度较高但计算量大;PF采用蒙特卡罗方法,鲁棒性强但计算耗时;VDKF能够动态调整状态维度,适合信标数量变化的场景。 适合人群:从事水下机器人(AUV)导航研究的技术人员、研究生以及对非线性滤波感兴趣的科研工作者。 使用场景及目标:①理解各种非线性滤波器的工作原理及其在水下定位中的具体应用;②评估不同滤波器在特定条件下的性能,以便为实际项目选择合适的滤波器;③掌握MATLAB实现非线性滤波器的方法和技术。 其他说明:文中提供了详细的MATLAB代码片段,帮助读者更好地理解和实现这些滤波器。此外,还讨论了数值稳定性问题和一些实用技巧,如Cholesky分解失败的处理方法。

    VMware-workstation-full-14.1.3-9474260

    VMware-workstation-full-14.1.3-9474260

    DeepSeek系列-提示词工程和落地场景.pdf

    DeepSeek系列-提示词工程和落地场景.pdf

    javaSE阶段面试题

    javaSE阶段面试题

    《综合布线施工技术》第5章-综合布线工程测试.ppt

    《综合布线施工技术》第5章-综合布线工程测试.ppt

    安川机器人NX100使用说明书.pdf

    安川机器人NX100使用说明书.pdf

    S7-1200 PLC改造M7120平面磨床电气控制系统:IO分配、梯形图设计及组态画面实现

    内容概要:本文详细介绍了将M7120型平面磨床的传统继电器控制系统升级为基于西门子S7-1200 PLC的自动化控制系统的过程。主要内容涵盖IO分配、梯形图设计和组态画面实现。通过合理的IO分配,确保了系统的可靠性和可维护性;梯形图设计实现了主控制逻辑、砂轮升降控制和报警逻辑等功能;组态画面则提供了友好的人机交互界面,便于操作和监控。此次改造显著提高了设备的自动化水平、运行效率和可靠性,降低了维护成本。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是熟悉PLC编程和控制系统设计的专业人士。 使用场景及目标:适用于需要进行老旧设备升级改造的企业,旨在提高生产设备的自动化水平和可靠性,降低故障率和维护成本。具体应用场景包括但不限于金属加工行业中的平面磨床等设备的控制系统改造。 其他说明:文中还分享了一些实际调试中的经验和技巧,如急停逻辑的设计、信号抖动的处理方法等,有助于读者在类似项目中借鉴和应用。

    chromedriver-linux64-136.0.7103.48.zip

    chromedriver-linux64-136.0.7103.48.zip

    IMG_20250421_180507.jpg

    IMG_20250421_180507.jpg

    《网络营销策划实务》项目一-网络营销策划认知.ppt

    《网络营销策划实务》项目一-网络营销策划认知.ppt

    Lianantech_Security-Vulnerabil_1744433229.zip

    Lianantech_Security-Vulnerabil_1744433229

    MybatisCodeHelperNew2019.1-2023.1-3.4.1.zip

    MybatisCodeHelperNew2019.1-2023.1-3.4.1

    《Approaching(Almost)any machine learning problem》中文版第13章(最后一章)

    【深度学习部署】基于Docker的BERT模型训练与API服务部署:实现代码复用与模型共享

    火车票订票系统设计与实现(代码+数据库+LW)

    摘  要 传统办法管理信息首先需要花费的时间比较多,其次数据出错率比较高,而且对错误的数据进行更改也比较困难,最后,检索数据费事费力。因此,在计算机上安装火车票订票系统软件来发挥其高效地信息处理的作用,可以规范信息管理流程,让管理工作可以系统化和程序化,同时,火车票订票系统的有效运用可以帮助管理人员准确快速地处理信息。 火车票订票系统在对开发工具的选择上也很慎重,为了便于开发实现,选择的开发工具为Eclipse,选择的数据库工具为Mysql。以此搭建开发环境实现火车票订票系统的功能。其中管理员管理用户,新闻公告。 火车票订票系统是一款运用软件开发技术设计实现的应用系统,在信息处理上可以达到快速的目的,不管是针对数据添加,数据维护和统计,以及数据查询等处理要求,火车票订票系统都可以轻松应对。 关键词:火车票订票系统;SpringBoot框架,系统分析,数据库设计

    【ABB机器人】-00标准保养简介.pdf

    【ABB机器人】-00标准保养简介.pdf

Global site tag (gtag.js) - Google Analytics