android 拖动图片拖动浮动按钮Word文档格式.docx
《android 拖动图片拖动浮动按钮Word文档格式.docx》由会员分享,可在线阅读,更多相关《android 拖动图片拖动浮动按钮Word文档格式.docx(14页珍藏版)》请在冰豆网上搜索。
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(Bundleicicle){
super.onCreate(icicle);
MyViewtx=newMyView(this);
tx.setText("
DragMe"
);
AbsoluteLayoutl=newAbsoluteLayout(this);
AbsoluteLayout.LayoutParamsp=newAbsoluteLayout.LayoutParams(
AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,10,10);
l.addView(tx,p);
setContentView(l);
}
}
classMyViewextendsButton{
publicMyView(Contextc){
super(c);
publicbooleanonMotionEvent(MotionEventevent){
intaction=event.getAction();
intmCurX=(int)event.getX();
intmCurY=(int)event.getY();
if(action==MotionEvent.ACTION_MOVE){
//this.setText("
x:
"
+mCurX+"
y:
+mCurY);
AbsoluteLayout.LayoutParamsp=new
AbsoluteLayout.LayoutParams(AbsoluteLayout.LayoutParams.WRAP_CONTENT,
AbsoluteLayout.LayoutParams.WRAP_CONTENT,this.mLeft+mCurX,this.mTop+
mCurY);
this.setLayoutParams(p);
if(action==MotionEvent.ACTION_UP){
notmoving"
returntrue;
publicvoiddraw(Canvascanvas){
//TODOAuto-generatedmethodstub
super.draw(canvas);
拖拽图片效果
方法一:
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.view.View.OnTouchListener;
importandroid.widget.ImageView;
publicclassDragSample01extendsActivity{
ImageViewimg;
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_sample01);
img=(ImageView)findViewById(R.id.img_view);
img.setOnTouchListener(newOnTouchListener(){
privateintmx,my;
publicbooleanonTouch(Viewv,MotionEventevent){
switch(event.getAction()){
caseMotionEvent.ACTION_MOVE:
mx=(int)(event.getRawX());
my=(int)(event.getRawY()-50);
v.layout(mx-img.getWidth()/2,my-img.getHeight()/2,mx+img.getWidth()/2,my+img.getHeight()/2);
break;
}});
方法二:
privatefloatx,y;
caseMotionEvent.ACTION_DOWN:
x=event.getX();
y=event.getY();
mx=(int)(event.getRawX()-x);
my=(int)(event.getRawY()-50-y);
v.layout(mx,my,mx+v.getWidth(),my+v.getHeight());
拖动按钮到处跑
1.布局文件
Xml代码
<
?
xmlversion="
1.0"
encoding="
utf-8"
>
LinearLayoutxmlns:
android="
android:
orientation="
vertical"
android:
layout_width="
fill_parent"
layout_height="
Buttonandroid:
id="
@+id/btn"
wrap_content"
text="
拖动看看~~"
/>
/LinearLayout>
2.代码
importandroid.util.DisplayMetrics;
publicclassDraftTestextendsActivity{
setContentView(R.layout.main);
finalButtonbtn=(Button)findViewById(R.id.btn);
btn.setOnTouchListener(newOnTouchListener(){
int[]temp=newint[]{0,0};
inteventaction=event.getAction();
intx=(int)event.getRawX();
inty=(int)event.getRawY();
switch(eventaction){
//touchdownsocheckifthe
temp[0]=(int)event.getX();
temp[1]=y-v.getTop();
//touchdragwiththeball
v.layout(x-temp[0],y-temp[1],x+v.getWidth()
-temp[0],y