自定义ImageView重写onTouchEvent

来源:互联网 发布:查看网络打印机端口ne 编辑:程序博客网 时间:2024/05/16 07:04

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>

原创粉丝点击