Search code examples
androidtoast

Toast not showing - Android


I've tried so many ways to show the Toast I want (on the DrawView Class) that I really don't know where to run anymore.

Apparently this is really simple, but I'm missing something. I've seen other related posts but had no success.

Any ideas please?

import android.app.Activity;
import android.os.Bundle;


public class MyActivity extends Activity{

    DrawView drawView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        drawView = new DrawView(this);
        setContentView(drawView);

    }

}

DrawView Class:

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;


public class DrawView extends View implements View.OnTouchListener{

    Paint paint = new Paint();

    public DrawView(MyActivity myActivity) {
        super(myActivity);

        setBackgroundColor(Color.WHITE);
        paint.setColor(Color.BLACK);

    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawText("I'm text in a canvas!", 10, 10, paint);

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN){

            Toast.makeText(getContext(),"I'm a Toast!",Toast.LENGTH_SHORT).show();

        }

        return false;

    }

}

Solution

  • public class DrawView extends View  {
    
    Paint paint = new Paint();
    private Context context;
    
    public DrawView(MainActivity context) {
        super(context);
        this.context = context;
        setBackgroundColor(Color.WHITE);
        paint.setColor(Color.BLACK);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
    
        canvas.drawText("I'm text in a canvas!", 10, 10, paint);
    
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
    
            Toast.makeText(context, "I'm a Toast!", Toast.LENGTH_SHORT).show();
    
        }
    
        return false;
    
    }}