我正在写一个 Android 画家。
这是我的主要内容:
package com.example.hwpainterandfilemanager;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
public class MainPainter extends Activity {
MyPainter painter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
painter = new MyPainter(getApplicationContext());
setContentView(R.layout.activity_main_painter);
}
@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_painter, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()){
case (R.id.Blue ):{
painter.mColor = Color.BLUE;
break;
}
case (R.id.Red ):{
painter.mColor=Color.RED;
break;
}
case (R.id.Yellow ):{
painter.mColor = Color.YELLOW;
break;
}
case (R.id.Green ):{
painter.mColor = Color.GREEN;
break;
}
}
return super.onOptionsItemSelected(item);
}
}
这是我的潘特:
package com.example.hwpainterandfilemanager;
import java.util.Vector;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class MyPainter extends View {
Vector<MyDot> allDots;
int mColor;
Paint p ;
public MyPainter(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}
public MyPainter(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
public MyPainter(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}
public void init(){
allDots = new Vector <MyDot> ();
mColor = Color.BLUE;
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
p= new Paint();
p.setStrokeWidth(5);
for (int i =0 ; i<allDots.size();i++){
p.setColor(allDots.get(i).mColor);
canvas.drawPoint(allDots.get(i).mX, allDots.get(i).mY, p);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int x,y;
if(MotionEvent.ACTION_DOWN==event.getAction() || MotionEvent.ACTION_MOVE==event.getAction()){
x= (int) event.getX();
y= (int) event.getY();
MyDot tmp;
tmp = new MyDot(x, y, mColor);
Log.i("Painter Color", "" + mColor);
allDots.add(tmp);
invalidate();
}
// TODO Auto-generated method stub
return true;
}
}
和 MyDot 类:
package com.example.hwpainterandfilemanager;
public class MyDot {
int mX =0;
int mY =0;
int mColor;
public MyDot (int x, int y, int color) {
mX=x;
mY=y;
mColor = color;
}
}
当尝试将颜色从蓝色更改为任何其他颜色时,颜色不会改变并保持不变。
我发现它工作的唯一方法是将 mColor 设置为静态,但这不是我想要解决这个问题的方式。
我错过了什么?
谢谢,阿夫纳。