本文实例讲述了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程序设计有所帮助。