在我的活动中,我尝试使用onClick
而不是覆盖onTouchEvent
方法,当我实施OnClickListener
并覆盖onClick
方法时,我没有得到任何结果。但是,使用onTouchEvent
方法并应用我的逻辑可以正常工作。
如何在我的活动中使用onClick
?
public class PixelParticle extends View{
private float locationX;
private float locationY;
private int sizeX;
private int sizeY;
private Paint color;
private Rect rect;
private int paintcolor;
public PixelParticle(Context context, float locationX, float locationY, int sizeX, int sizeY, int paintcolor) {
super(context);
this.locationX = locationX;
this.locationY = locationY;
this.sizeX = sizeX;
this.sizeY = sizeY;
this.paintcolor = paintcolor;
rect = new Rect();
color = new Paint();
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, sizeX, sizeY, true);
canvas.drawBitmap(myBitmap,locationX -(resizedBitmap.getWidth() / 2) ,locationY - (resizedBitmap.getHeight() / 2), null);
}
}
...
public class MainActivity extends Activity implements OnClickListener{
private int pixelColor;
private float x;
private float y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//removes title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//sets view to full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@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;
}
public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
pixelColor = Color.RED;
PixelParticle pp = new PixelParticle(this, x, y, 50, 50, pixelColor);
setContentView(pp);
return false;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
当我评论onTouchEvent
并在onClick
内写相同的代码时,没有任何反应。
和XML布局
<RelativeLayout 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"
tools:context=".MainActivity"
android:onClick="onClick" >
</RelativeLayout>
答案 0 :(得分:0)
您可以查看已触发的触摸事件类型,并使用该事件确定是否重绘。
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
// Do your drawing here..
return false;
}
return true;
}
希望有所帮助。