-4

I need to create custom Toast like component. This should appears over only my application to show some message.

Why i don't use android Toast - because i need custom duration.

Problem is I'm creating view through WindowManager.addView with type WindowManager.LayoutParams.TYPE_APPLICATION

But it works only over 1 Activity, when i close it, toast disappears.

But I have a lot of places - where i open an activity to do some task, and after success result i should immediately show toast and close this Activity.

I need to keep toast over all my activities, but not over android system. And i don't want to use TYPE_SYSTEM_ALERT because it's require additional permission

Is there some method to sure do that? Use of WindowManager is not required.

reiley
  • 3,759
  • 12
  • 58
  • 114
  • Please don't ask question like SMS. Provide line spaces, punctuations and your example code snippet. SO is a contributing community, so phrase your questions so others can use as well. I've rephrased it a bit. Good luck!! – reiley Jul 15 '19 at 09:06

1 Answers1

1

try it methood Custom Toast

public static void Toast(String textmessage) {

    LinearLayout layout = new LinearLayout(getContext());
    layout.setBackgroundResource(R.drawable.shape_toast);
    layout.setPadding(30, 30, 30, 30);

    TextView tv = new TextView(getContext());
    tv.setTextColor(Color.WHITE);
    tv.setTextSize(12);
    tv.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/font.ttf"));

    tv.setGravity(Gravity.CENTER);
    tv.setText(textmessage);

    layout.addView(tv);

    Toast toast = new Toast(getContext());
    toast.setView(layout);

    toast.setGravity(Gravity.BOTTOM, 0, 240);
    toast.show();

}

you can try it methood Toast with duration

public class ToastExpander {

    public static final String TAG = "ToastExpander";

    public static void showFor(final Toast aToast, final long durationInMilliseconds) {

        aToast.setDuration(Toast.LENGTH_SHORT);

        Thread t = new Thread() {
            long timeElapsed = 0l;

            public void run() {
                try {
                    while (timeElapsed <= durationInMilliseconds) {
                        long start = System.currentTimeMillis();
                        aToast.show();
                        sleep(1750);
                        timeElapsed += System.currentTimeMillis() - start;
                    }
                } catch (InterruptedException e) {
                    Log.e(TAG, e.toString());
                }
            }
        };
        t.start();
    }
}

and for show toast use this

Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);