android实现拖动效果
16lz
2022-06-19
1. 布局文件
view plain copy to clipboard print ?- <?xml version = "1.0" encoding = "utf-8" ?>
- <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
- android:orientation = "vertical" android:layout_width = "fill_parent"
- android:layout_height = "fill_parent" >
- <Button android:id = "@+id/btn_hello" android:layout_width = "fill_parent"
- android:layout_height = "wrap_content" android:text = "@string/hello" />
- </LinearLayout>
2. 代码
view plain copy to clipboard print ?- package com.roiding.sample;
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.View.OnTouchListener;
- import android.widget.Button;
- public class Touch extends Activity{
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- public void onCreate(BundlesavedInstanceState){
- super .onCreate(savedInstanceState);
- setContentView(R.layout.main);
- final Buttonbtn=(Button)findViewById(R.id.btn_hello);
- btn.setOnTouchListener( new OnTouchListener(){
- int []temp= new int []{ 0 , 0 };
- public boolean onTouch(Viewv,MotionEventevent){
- int eventaction=event.getAction();
- Log.i( "&&&" , "onTouchEvent:" +eventaction);
- int x=( int )event.getRawX();
- int y=( int )event.getRawY();
- switch (eventaction){
- case MotionEvent.ACTION_DOWN: //touchdownsocheckifthe
- temp[ 0 ]=( int )event.getX();
- temp[ 1 ]=y-v.getTop();
- break ;
- case MotionEvent.ACTION_MOVE: //touchdragwiththeball
- v.layout(x-temp[ 0 ],y-temp[ 1 ],x+v.getWidth()
- -temp[ 0 ],y-temp[ 1 ]+v.getHeight());
- v.postInvalidate();
- break ;
- case MotionEvent.ACTION_UP:
- break ;
- }
- return false ;
- }
- });
- }
- }
更多相关文章
- Android(安卓)SDCard操作(文件读写,容量计算)
- android source code下载源代码时出错
- ViewPager添加动画效果(一行代码)
- Android(安卓)模拟登陆 保存密码(信息)到手机中 文件信息读取
- Android字体设置
- 编译代码报出Android(安卓)library projects cannot be launched
- android上传图片至服务器
- android读取SDCard任意路径下的文件
- NPM 和webpack 的基础使用