Reputation: 1342
I have a Custom View which is stored in a XML Layout. The XML Layout is the View for my Activity. I am able to reference to the Custom View inside the XML Layout from my Activity, just as you would for any Android Widget. I can then get the onTouch listener which works fine. What I want to be able to do is reference to a method inside my Custom View which will enable me to draw on the Canvas. I have tied by Using the following code but have had no success. Any help would be much appreciated. PS My code does much more than this, I have just listed what I think is most necessary.
public class DrawView extends View {
public Canvas;
public Paint textPaint = new Paint()
public DrawView(Context context, AttributeSet attributeSet) {
super.DrawView(context attributeSet)
textPaint.setColor(getResources().getColor(R.color.text));
}
@Override
onDraw(Canvas canvas) {
mCanvas = canvas;
}
public void drawText() {
mCanvas.drawText("text", 100, 100, textPaint);
}
}
MainActivity:
public class MainActivity extends Activity {
DrawView mDrawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sch_main);
//Get Handlers To DrawView
mDrawView = (DrawView) findViewById(R.id.draw);
//Get onTouch from DrawView
mDrawView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
}
else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
}
else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
mDrawView.drawText();
}
return false;
}
});
}
}
Layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<example.DrawLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/draw"/>
</LinearLayout>
Upvotes: 1
Views: 234
Reputation: 20179
You can't hold on to the Canvas
passed to onDraw
and paint whenever you like, you can only draw on the canvas when onDraw
is called.
You should rethink the design of DrawView
: have fields storing data about what should be drawn, allow methods to change these fields and do the actual drawing inside onDraw
based on those fields. In your simple case, you could store a boolean
field to indicate if the text should be drawn (e.g. isTextVisible
), have a method to set it to true
and draw it inside onDraw
if the field value is true
.
You can choose to make your methods force a redraw by calling invalidate()
, so the changes are made effective immediately.
Upvotes: 3