<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:id="@+id/mylayout" tools:context="com.example.sl3_4.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </FrameLayout>
MainActivity.java
package com.example.sl3_4; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.FrameLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout frameLayout=(FrameLayout)findViewById(R.id.mylayout); final RabbitView rabbit=new RabbitView(MainActivity.this); //为小兔子添加触发事件监听器 rabbit.setOnTouchListener(new OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event) { // TODO 自动生成的方法存根 rabbit.bitmapX=event.getX(); rabbit.bitmapY=event.getY(); rabbit.invalidate();//重绘rabbit组件 return false; } }); frameLayout.addView(rabbit); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
RabbitView.java类
package com.example.sl3_4; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; public class RabbitView extends View { public float bitmapX; public float bitmapY; public RabbitView(Context context) { super(context); bitmapX=750; bitmapY=500; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint=new Paint(); Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(),R.drawable.rabbit); canvas.drawBitmap(bitmap,bitmapX,bitmapY, paint); if(bitmap.isRecycled()) //强制回收图片 { bitmap.recycle(); } } }
小兔子图片