我正在将SurfaceView作为我的xml文件中的customView实现。我想为它添加ontouch方法。但它目前没有绘制图标图像。任何人请帮助我,请回答如何添加ontouch方法。
我的xml文件。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:gif="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<rahul.surfacetest.ImageClass
android:id="@+id/viw"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="@drawable/them"
android:layout_centerInParent="true"
android:paddingTop="200dp" />
</RelativeLayout>
它是我的主要课程
public class MainActivity extends Activity{
ImageClass Is;
static float x,y=0;
Bitmap bmp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Is=(ImageClass)findViewById(R.id.viw);
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
}
它是我的表面类
public class ImageClass extends SurfaceView implements OnTouchListener,Runnable {
float x,y;
SurfaceHolder holder;
boolean isItOk = true;
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Paint p = new Paint();
public ImageClass(Context context, AttributeSet attrs) {
super(context, attrs);
y=x=10;
holder = getHolder();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x=event.getX();
y=event.getY();
break;
case MotionEvent.ACTION_UP:
x=event.getX();
y=event.getY();
break;
case MotionEvent.ACTION_MOVE:
x=event.getX();
y=event.getY();
break;
default:
break;
}
return true;
}
@Override
public void run() {
Canvas c = holder.lockCanvas();
c.drawBitmap(bmp, x,y, null);
holder.unlockCanvasAndPost(c);
}
}