安卓中利用OnGestureListener对控件进行手势滑动事件的处理

网上有很多关于对OnGestureListener监听的文章,但是今天我真的需要用到对手势滑动事件进行监听的时候,搜的这些文章里面却有的不会捕获到onFling的事件。这是为什么呢?通过网上搜索找到了一些解决的办法,并且自己也来尝试试验一下哪种是正确的。

我是想制作一个短信监听器,里面分为黑名单和白名单,对于黑名单里面的对象发来的短信直接屏蔽掉,对于白名单里面的对象发来的内容采取Toast提示的方式,节省了点开短信这个步骤。

对于首页对名单进行操作,实现了如下的界面:

安卓中利用OnGestureListener对控件进行手势滑动事件的处理_第1张图片



操作步骤,首先我们需要实现两个接口:

MangerUser implements OnTouchListener,OnGestureListener

当然你也完全可以自己重新创建一个类来实现这两个接口,像我就是写在了一个layout里面。但是一般还是建议放在acticity里面,原因很简单,activity中的方法对象多可以直接调用,不用传对象传值了。

实现了这两个接口之后会默认添加以下的7中方法,其中

OnTouchListener下有:

@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}
OnGestureListener下游:
@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}


这里面每个方法就不详细介绍其作用了,反正对我们最有用的就是onFling这个监听手势滑动的。

MotionEvent e1, MotionEvent e2, float velocityX,float velocityY

作用是:

e1  The first down motion event that started the fling.首次手势点的移动事件   
e2  The move motion event that triggered the current onFling.移动动作事件引发了当前的手势点事件
velocityX   The velocity of this fling measured in pixels per second along the x axis.每秒x轴方向移动的像素   
velocityY   The velocity of this fling measured in pixels per second along the y axis.每秒y轴方向移动的像素 

有了这四个参数,想想手势解锁手机屏幕,愤怒的小鸟,小鳄鱼洗澡。。。。你懂得。很管用。

好了,剩下的就不多说了。。直接奔主题!

public class MangerUser implements OnTouchListener,OnGestureListener{
	private Context context;
	private Activity ac;
	private TextView showblackname;
	private TextView showblacknum;
	private TextView showwhitename;
	private TextView showwhitenum;
	
	private Map<String,String> map;//Map<Photo,Name>
	private SharedPreferences whitesp;
	private SharedPreferences blacksp;
	private Editor editor;
	private Button showwhitelist;
	private Button showblacklist;
	private Button selectbtn;
	
	private ViewFlipper showuser;
	private static String whiteSPname="phone_name_white";
	private static String blackSPname="phone_name_black";
	
	//手势事件对象
	private GestureDetector detector;
	
	private int flag;//标记位,标记位为0时代表此时的状态是不可操作,为1时代表此时的状态是控制白名单,为-1时代表此时的状态是控制黑名单
	
	
	public MangerUser(Context context) {
		this.context=context;
		ac=(Activity)context;
		detector=new GestureDetector(this);
		init();
	}

	public void init() {
		flag=0;
		showblackname=(TextView) ac.findViewById(R.id.showblackname);
		showblacknum=(TextView) ac.findViewById(R.id.showblacknum);
		
		showwhitename=(TextView) ac.findViewById(R.id.showwhitename);
		showwhitenum=(TextView) ac.findViewById(R.id.showwhitenum);
		
		showwhitelist=(Button)ac.findViewById(R.id.whitebtn);
		showblacklist=(Button)ac.findViewById(R.id.blackbtn);
		
		selectbtn=(Button)ac.findViewById(R.id.selectbtn);
		selectbtn.setOnTouchListener(this);//一定要加上
		selectbtn.setLongClickable(true); //如果不设置为true,对象就不会响应onTouch事件,

		
		showuser=(ViewFlipper) ac.findViewById(R.id.showuser);
		
		startListen();
		showwhitelist.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					
				}
				if(event.getAction()==MotionEvent.ACTION_UP){
					showWhiteList();
				}
				
				return true;
			}
		});
		
		showblacklist.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					
				}
				if(event.getAction()==MotionEvent.ACTION_UP){
					showBlackList();
				}
				
				return true;
			}
		});
		
		blacksp=context.getSharedPreferences(blackSPname, Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
		whitesp=context.getSharedPreferences(whiteSPname, Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
		showUser();
	}
	
	//从数据库中读出数据,添加到set当中,并且显示白名单列表
	public void showWhiteList(){
		//显示白名单
		if(showuser.getDisplayedChild() == 0){//如果滑动到最后
			showuser.stopFlipping();                                   //停止切换
			System.out.println("白名单停止切换");
		}else{
			showuser.setInAnimation(context,
					R.anim.push_left_in);
			showuser.setOutAnimation(context,
					R.anim.push_right_out);
			showuser.showNext();
			editor=whitesp.edit();
			this.flag=1;
			
		}
	}
	
	//从数据库中读出数据,添加到set当中,并且显示黑名单列表
	public void showBlackList(){
		//显示黑名单
		if(showuser.getDisplayedChild() == 1){//如果滑动到最后
			showuser.stopFlipping();                                   //停止切换
			System.out.println("黑名单停止切换");
		}else{
		showuser.setInAnimation(context,
				R.anim.push_right_in);
		showuser.setOutAnimation(context,
				R.anim.push_left_out);
		showuser.showNext();
		editor=blacksp.edit();
		this.flag=-1;
		}
	}

	
	public void startListen() {
		// TODO Auto-generated method stub
		Button addbtn = (Button) ac.findViewById(R.id.addbtn);
		Button deletebtn = (Button) ac.findViewById(R.id.deletebtn);
		addbtn.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					
				}
				//按钮释放
				if(event.getAction() == MotionEvent.ACTION_UP){
					saveUser();
				}
				return true;
			}
		});
		deletebtn.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					
				}
				//释放
				else if(event.getAction() == MotionEvent.ACTION_UP){
					deleteUser();
				}
				return true;
			}
		});

	}
	
	public void saveUser(){
		if(canAction())return;
		SharedPreferences sp;
		if(flag==1){
			sp=whitesp;
			System.out.println("保存白名单用户");
		}else{
			sp=blacksp;
			System.out.println("保存黑名单用户");
		}
		//获取处理对象
		map=(Map<String, String>) sp.getAll();
		TextView nameedit=((TextView) ac.findViewById(R.id.input_name));
		TextView telephoneedit=((TextView) ac.findViewById(R.id.input_num));
		String name=nameedit.getText().toString();
		String telephone=telephoneedit.getText().toString();
		if(!Pattern.compile("[A-Za-z]+\\w{0,10}").matcher(name).matches()){
			Toast.makeText(ac, "输入的名字不合法", Toast.LENGTH_SHORT).show();
		}else{
			if(!Pattern.compile("\\d{7,11}").matcher(telephone).matches()){
				Log.w("tag","输入的电话不合法!"+telephone );
				Toast.makeText(ac, "输入的电话不合法", Toast.LENGTH_SHORT).show();
			}else{
				if(map.get(telephone)!=null){
					Toast.makeText(ac, "用户已存在", Toast.LENGTH_SHORT).show();
				}else{
					editor.putString(telephone, name);
					Toast.makeText(ac, "添加成功", Toast.LENGTH_SHORT).show();
				}
				nameedit.setText("");
				telephoneedit.setText("");
			}
		}
		editor.commit();
		showUser();
	}
	public void deleteUser(){
		if(canAction())return;
		TextView inputname=((TextView) ac.findViewById(R.id.input_name));
		TextView inputtelephone=((TextView) ac.findViewById(R.id.input_num));
		String name=inputname.getText().toString();
		String telephone=inputtelephone.getText().toString();
		if(Pattern.compile("[A-Za-z]+\\w{0,10}").matcher(name).matches()){
			//进行删除
			removeByName(name);
			inputname.setText("");
			inputtelephone.setText("");
			Toast.makeText(ac, "用户"+name+"删除成功", Toast.LENGTH_SHORT).show();
		}else{
			if(Pattern.compile("\\d{7,11}").matcher(telephone).matches()){
				removeByTelephoto(telephone);
				inputname.setText("");
				inputtelephone.setText("");
				Toast.makeText(ac, "用户电话"+telephone+"删除成功", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(ac, "不存在该用户的姓名或者电话", Toast.LENGTH_SHORT).show();
			}
		}
		showUser();
	}
	
	public boolean canAction(){
		if(flag==0){
			Toast.makeText(context, "请先选择名单", Toast.LENGTH_LONG).show();;
			return true;
		}
		return false;
	}
	
	private void removeByTelephoto(String telephone) {
		editor.remove(telephone);
		editor.commit();
	}
	
	private void removeByName(String name) {
		SharedPreferences sp;
		if(flag==1){
			sp=whitesp;
		}else{
			sp=blacksp;
		}
		
		Map<String, ?> all = sp.getAll();
		for(String tetephone:all.keySet()){
			if(name.equals(all.get(tetephone))){
				editor.remove(tetephone);
			}
		}
		editor.commit();
	}

	public void showUser(){
		Map<String, ?> whitemap = whitesp.getAll();
		Map<String, ?> blackmap = blacksp.getAll();
		Log.v("show whiteuser size", whitemap.size()+"");
		Log.v("show blackuser size", blackmap.size()+"");
		
		StringBuilder whitenamestr=new StringBuilder("姓名(白)");
		StringBuilder whitenumstr=new StringBuilder("电话(白)");
		for(String photo:whitemap.keySet()){
			whitenumstr.append("\n"+photo);
			whitenamestr.append("\n"+whitemap.get(photo));
		}
		showwhitename.setText(whitenamestr);
		showwhitenum.setText(whitenumstr);
		
		StringBuilder blacknamestr=new StringBuilder("姓名(黑)");
		StringBuilder blacknumstr=new StringBuilder("电话(黑)");
		for(String photo:blackmap.keySet()){
			blacknumstr.append("\n"+photo);
			blacknamestr.append("\n"+blackmap.get(photo));
		}
		showblackname.setText(blacknamestr);
		showblacknum.setText(blacknumstr);
	}

	public Context getContext(){
		return context;
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		System.out.println("in onfling");
		if (e1.getX() > e2.getX()) {// move to left
			showBlackList();
			System.out.println("in onfling move to left");
		} else if (e1.getX() < e2.getX()) {
			showWhiteList();
			System.out.println("in onfling move to right");
		} else {
			return false;
		}
		//返回值的问题,如果这里返回的是false,则此次事件未处理完成,继续进行
		//返回为true的话,表示事件到此为止,则不进行
		//如有有兴趣的话可以做一个实验,这里改成true之后按钮被划过之后就一直处于被点中状态。
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		System.out.println("被调用");
		return detector.onTouchEvent(event);
	}

	public ViewFlipper getShowuser() {
		return showuser;
	}

	public void setShowuser(ViewFlipper showuser) {
		this.showuser = showuser;
	}
}




你可能感兴趣的:(安卓中利用OnGestureListener对控件进行手势滑动事件的处理)