1 MoveImageView
package com.android.tian;
import android.content.Context;
import android.util.AttributeSet;
import android.view.*;
import android.widget.ImageView;
public class MoveImageView extends ImageView {
public MoveImageView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MoveImageView(Context context,AttributeSet attrs) {
super(context,attrs);
// TODO Auto-generated constructor stub
}
public MoveImageView(Context context,AttributeSet attrs,int defStyle) {
super(context,attrs,defStyle);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
//return super.onTouchEvent(event);
int eventaction = event.getAction();
switch(eventaction){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
{
//在这里设置的话效果就是一顿神闪......
//int X = (int) event.getX();
//int Y = (int) event.getY();
//if( X > 0 && Y > 0)
// this.layout(X, Y,X + this.getWidth(),Y + this.getHeight());
break;
}
case MotionEvent.ACTION_UP:
{
int x = (int)event.getX();
int y = (int)event.getY();
if(x>0&&y>0){
this.layout(x,y,x+this.getWidth(),y+this.getHeight());
}
break;
}
}
this.invalidate();
return true;
}
}
2 MainActivity.java
package com.android.tian;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import com.android.tian.MoveImageView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
LayoutInflater inflater = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout)findViewById(R.id.test_layout);
MoveImageView moveImage = new MoveImageView(this);
moveImage.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
moveImage.setBackgroundResource(R.drawable.icon);
layout.addView(moveImage);
}
}
3 main。xml
<?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"
android:id="@+id/test_layout"
>
</LinearLayout>