سؤال

Toast.makeText(getApplicationContext(), getString(R.string.negative), Toast.LENGTH_SHORT).show();

How do I set a time appearance for this and make this cancelable. Also how do I set this one to appear in the middle part of the screen ?

هل كانت مفيدة؟

المحلول

1. For time appearance : Duration

There two cases : Toast.LENGTH_SHORT (display in short period of time) or Toast.LENGTH_LONG (display in long period of time).

You cannot define a time appearance for toasts

2. Toast gravity : (display in the middle of screen) :

You can position the Toast as we desire using a method named setGravity() which has got three parameters: gravity , x-offset , y-offset.

toast.setGravity(Gravity.CENTER, 0, 0); // toast in the center of screen

EDIT : For your case you can use :

Toast toast= Toast.makeText(getApplicationContext(), getString(R.string.positive), Toast.LENGTH_LONG);  
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

نصائح أخرى

The time the toast is shown is specified here:

 Toast.LENGTH_SHORT

in your code. You can only use Toast.LENGTH_SHORT or Toast.LENGTH_LONG ==> Toast is not very flexible with the timing, but they don't need to be, see documentation:

When the view is shown to the user, appears as a floating view over the application. It will never receive focus. The user will probably be in the middle of typing something else. The idea is to be as unobtrusive as possible, while still showing the user the information you want them to see. Two examples are the volume control, and the brief message saying that your settings have been saved.

I don't think you can do that with Toasts. You may want to look a AlertDialogs

Check out this library that does almost all the things you requested. It is called MessageBar and is meant to be a replacement for Android's Toast.

As for changing the position of the Toast bar check out this SO answer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top