import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.style.AbsoluteSizeSpan; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AbsoluteLayout; import android.widget.Button; public class HelloWorld2 extends Activity { /** Called when the activity is first created. */ AbsoluteLayout mLayoutGroup = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.main); mLayoutGroup = new AbsoluteLayout(this); AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams (320, 480, 0, 0); setContentView(mLayoutGroup, layoutParams); Button button= new Button(this); button.setText("testButton"); layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 20); mLayoutGroup.addView(button, layoutParams); button.setOnTouchListener(touchListener); final Button btButton = new Button(this); btButton.setText("测试按钮移动"); layoutParams = new AbsoluteLayout.LayoutParams(120, 60, 20, 160); mLayoutGroup.addView(btButton, layoutParams); btButton.setOnTouchListener(touchListener); } OnTouchListener touchListener = new OnTouchListener() { int temp[] = new int[]{0, 0}; public boolean onTouch(View arg0, MotionEvent arg1) { // TODO Auto-generated method stub int eventAction = arg1.getAction(); Log.e("testButtonMove", "OnTouchAction:"+eventAction); int x = (int)arg1.getRawX(); int y = (int)arg1.getRawY(); switch (eventAction) { case MotionEvent.ACTION_DOWN: temp[0] = (int)arg1.getX(); temp[1] = (int)(y-arg0.getTop()); mLayoutGroup.bringChildToFront(arg0); arg0.postInvalidate(); break; case MotionEvent.ACTION_MOVE: int left = x - temp[0]; int top = y - temp[1]; int right = left + arg0.getWidth(); int bottom = top + arg0.getHeight(); arg0.layout(left, top, right, bottom); arg0.postInvalidate(); break; default: break; } return false; } }; }
http://gundumw100.iteye.com/blog/960589