Domanda

i'm trying to show a Toast message with a custom view i created. the view has a bitmap on the background and i want to write some text on it.

if I assign the bitmap to an ImageView on the main code I manage to make it show up with Toast t; (...) t.show(); but when it's the onDraw() method of my class to assign the bitmap nothing shows up. i checked, and my view has a size of (0, 0) when created the way i transcribe under.

help please.

Main.java

    Toast t = new Toast(this);
    LimitView lv = new LimitView(this);

    t.setView(lv);
    t.setDuration(Toast.LENGTH_LONG);
    t.show();

LimitView.java

public void onDraw(Canvas canvas)
{
    super.onDraw(canvas);

    canvas.save();

    canvas.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.limit));

    canvas.restore();
}
È stato utile?

Soluzione

try this code:

Main.java

Context context = this;

Toast t = new Toast(context);
LeftBorder lv = new LimitView(context);
t.setView(lv);
t.setDuration(Toast.LENGTH_LONG);
t.show();

LimitView.java

public class LimitView extends View {
    public LimitView (Context context) {
        super(context);
    }

    protected void onDraw(Canvas canvas){
        super.onDraw(canvas);
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button_pressed), getMatrix(), new Paint());
    }
}

Altri suggerimenti

There are several errors here.

BitmapFactory.decodeResource(getResources(), R.drawable.limit)

This is a heavy operation and should not be on view drawing phase.

canvas.setBitmap();

This method does not drawing bitmap on canvas but setting the canvas buffer to use this bitmap.

Try some thing like this:

public class MyView extends View{

    private Bitmap bitmap;

    public MyView(Context context) {
        super(context);
        bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.limit);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, null);
    }

}
replace this 

canvas.setBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.limit));

to this:

canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.button_pressed),left,top, new Paint());

here left and right are the position of the screen.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top