欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android基于widget组件实现物体移动/控件拖动功能示例

程序员文章站 2024-03-03 16:19:28
本文实例讲述了android基于widget组件实现物体移动/控件拖动功能。分享给大家供大家参考,具体如下: package com.sky; import a...

本文实例讲述了android基于widget组件实现物体移动/控件拖动功能。分享给大家供大家参考,具体如下:

package com.sky;
import android.app.activity;
import android.os.bundle;
import android.view.keyevent;
import android.view.motionevent;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.absolutelayout;
import android.widget.button;
@suppresswarnings("deprecation")
public class abosolutemove extends activity implements onclicklistener
{
 /** called when the activity is first created. */
 public button button1;
 public button button2;
 public button button3;
 public button button4;
 button tmp;//临时保存,选择的button
 int x;
 int y;
 int flag;//用于标志选择哪个button
  @override
  public void oncreate(bundle savedinstancestate)
  {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);
    button1=(button) findviewbyid(r.id.widget27);
    button2=(button) findviewbyid(r.id.widget28);
    button3=(button) findviewbyid(r.id.widget29);
    button4=(button) findviewbyid(r.id.widget30);
    button1.setonclicklistener(this);
    button2.setonclicklistener(this);
    button3.setonclicklistener(this);
    button4.setonclicklistener(this);
  }
 @override
 public void onclick(view v)
 {
 // todo auto-generated method stub
 switch(v.getid())
 {
  case r.id.widget27:
  flag=r.id.widget27;
  settitle("button1");
  break;
  case r.id.widget28:
  flag=r.id.widget28;
  settitle("button2");
  break;
  case r.id.widget29:
  flag=r.id.widget29;
  settitle("button3");
  break;
  case r.id.widget30:
  flag=r.id.widget30;
  settitle("button4");
  break;
 }
 }
 @override
 public boolean onkeydown(int keycode, keyevent event)
 {
 // todo auto-generated method stub
 return super.onkeydown(keycode, event);
 }
 @override
 public boolean ontouchevent(motionevent event)
 {
 // todo auto-generated method stub
 x = (int) event.getx();
    y = (int) event.gety();
    tmp=(button) findviewbyid(flag);//获取所选中的button
    absolutelayout.layoutparams params1=new absolutelayout.layoutparams(50,50,x-25,y-50);
    tmp.setlayoutparams(params1);//设置button的新位置
    switch(event.getaction())
    {
      case motionevent.action_down:
       tmp.invalidate();
       tmp.settext("选中down");
        break;
      case motionevent.action_up:
       tmp.invalidate();
       tmp.settext("选中up");
        break;
      case motionevent.action_move:
       tmp.invalidate();
       tmp.settext("选中move");
        break;
    }
    return super.ontouchevent(event);
 }
}

更多关于android相关内容感兴趣的读者可查看本站专题:《android基本组件用法总结》、《android开发入门与进阶教程》、《android资源操作技巧汇总》、《android视图view技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。