我想点击一个按钮并添加一个电阻。所以我需要的是在单击按钮时使视图无效。但是方法MyView
内的update()
内的无效值无效。我一直试图寻找这个问题,但我发现没有什么类似于我想做的事情,或者这可能不是这样做的。
DefaultActivity.java
public class DefaulActivity extends Activity {
MyView myView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myView = new MyView(this, null);
final Button bAddResistor = (Button) findViewById(R.id.bAdd);
bAddResistor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
myView.update();
Log.d("ButtonADD", "Button Add has been clicked");
}
});
}
}
MyView.java
public class MyView extends SurfaceView implements SurfaceHolder.Callback{
Resistor myResistor;
private ArrayList<Resistor> mElements = new ArrayList<Resistor>();
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
synchronized (mElements) {
for (Resistor element : mElements) {
element.doDraw(canvas);
}
}
}
public void update() {
mElements.add(new Resistor(getContext(), (int) 10, (int) 10));
invalidate(); //Does not work!
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = holder.lockCanvas();
onDraw(c);
holder.unlockCanvasAndPost(c);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
Resistor.java
public class Resistor extends View{
private Path mSymbol;
private Paint mPaint;
private int mX;
private int mY;
//...Override Constructors...
public Resistor(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Resistor(Context context, int x, int y){
super(context);
mX = x;
mY = y;
init();
}
private void init() {
mSymbol = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(2);
mPaint.setColor(-7829368);
mPaint.setStyle(Paint.Style.STROKE);
//...Your code here to set up the path,
//...allocate objects here, never in the drawing code.
mSymbol.moveTo(0.0F, 0.0F);
mSymbol.lineTo(0.0F, 50.0F);
mSymbol.lineTo(16.666666F, 58.333332F);
mSymbol.lineTo(-16.666666F, 75.0F);
mSymbol.lineTo(16.666666F, 91.666664F);
mSymbol.lineTo(-16.666666F, 108.33333F);
mSymbol.lineTo(16.666666F, 124.99999F);
mSymbol.lineTo(-16.666666F, 141.66666F);
mSymbol.lineTo(0.0F, 150.0F);
mSymbol.lineTo(0.0F, 200.0F);
mSymbol.offset(mX, mY);
}
public void doDraw(Canvas canvas) {
canvas.drawPath(mSymbol, mPaint);
}
答案 0 :(得分:0)
您应该使用ViewGroup
代替SurfaceView
。将Resistor
- 视图作为子项添加到MyView
,measure and layout them appropriately,ViewGroup
将自动处理它们。
SurfaceView
要求您在单独的帖子中进行绘图。您必须在surfaceCreated
中启动该线程,并根据需要不断重绘视图。对于像你发布的那样的简单视图,在UI线程中进行绘图是完全可以接受的。不需要SurfaceView
。
答案 1 :(得分:0)
之前我没有使用过Surfaceview,但如果您在API中可以看到,SurfaceView类中没有名为“invalidate()”的函数。
也许你可以设法以某种方式重复使用这条线:
holder.unlockCanvasAndPost(c);