/ / Invalidate nezavoláDraw - android, android-plátno

Invalidate nevolá programDraw - android, android-canvas

Potrebujem kliknutím na tlačidlo prepísať obrázok, ale po zrušení metódyDraw metóda nie je volaná. Aplikácia Draca sa však spustí až po spustení aplikácie.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Draw draw = new Draw(this);

Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
draw.setA(40);
draw.setB(300);
draw.invalidate();
}
});

}
}

Tu je kód Draw.java

public class Draw extends View {

private Paint mPaint;
private int a;
private int b;

public Draw(Context context) {
super(context);
init();
}

public Draw(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public Draw(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

private void init() {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(5);
setWillNotDraw(false);
a = 0;
b = 0;
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(Color.WHITE);
canvas.drawPaint(mPaint);

mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
canvas.drawLine(80, 50, 80, 500, mPaint);
canvas.drawLine(80, 50, 70, 85, mPaint);
canvas.drawLine(80, 50, 90, 85, mPaint);

canvas.drawLine(80, 500, 500, 500, mPaint);
canvas.drawLine(500, 500, 465, 510, mPaint);
canvas.drawLine(500, 500, 465, 490, mPaint);

mPaint.setTextSize(35);
mPaint.setStrokeWidth(2);
canvas.drawText("X", 480, 540, mPaint);
canvas.drawText("Y", 45, 80, mPaint);
canvas.drawText("0", 70, 540, mPaint);

drawFunction(canvas, a, b);
}

public void drawFunction(Canvas canvas, int a, int b) {

mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
canvas.drawLine(80, 500, a, b, mPaint);
}

public void setA(int a) {
this.a = a;
}

public void setB(int b) {

this.b = b;
}
}

main.xml

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<labs.example.function.Draw
android:layout_width="match_parent"
android:layout_height="wrap_content">

</labs.example.function.Draw>
</RelativeLayout>

Vopred ďakujem.

odpovede:

3 pre odpoveď č. 1

Pridajte id

<labs.example.function.Draw
android:id="@id/draw"
android:layout_width="match_parent"
android:layout_height="wrap_content">

</labs.example.function.Draw>

vymeniť

 final Draw draw = new Draw(this);

podľa

 final Draw draw = (Draw) findViewById(R.id.draw); // need to refer to the view in xml.

Ak používate final Draw draw = new Draw(this); musíte tento pohľad pridať do hierarchie zobrazenia.


0 pre odpoveď č. 2

Pokúsili ste sa zavolať setWillNotDraw(false), V tomto pošta môžete si všimnúť, že predvolene všetky podtriedy ViewGroup nevyzývajú ich onDraw metóda.