I want to know how to display toast programmaticaly. When I read the data from the database, I can only see the toast for short time, even though the length of the text is small or bigger. But I want to see the toast visible for little longer(At least for 3-5 seconds).

有帮助吗?

解决方案

Something like this might suit your needs :

String stringFromDatabase = "your string";

if (stringFromDatabase.length()<200){
    Toast.make(context, stringFromDatabase, Toast.LENGTH_SHORT).show();
}else{
    Toast.make(context, stringFromDatabase, Toast.LENGTH_LONG).show();
}

This will show your Toast for a short or long time, depending on the length of your String.

其他提示

Toast is displayed as below.

Toast.makeText(getApplicationContext(), textToDisplay, 
   Toast.LENGTH_LONG).show();

The parameter Toast.LENGTH_LONG tells that it should display for long. May be u need to change it to LENGTH_LONG.

You will have to implement a custom Toast if you want to display the message for longer time. The values of LENGTH_SHORT and LENGTH_LONG are 0 and 1. They don't specify an amount of time.

Unfortunately, the longest time a toast can be displayed is 3.5 seconds(for LENGTH_LONG, while LENGTH_SHORT is 2 seconds).

If you want a shorter toast you can cancel it after a pause - for example:

final Toast toast = Toast.makeText(getApplicationContext(), "your string", Toast.LENGTH_SHORT);
    toast.show();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            toast.cancel();
        }
    }, 500);

Will display for 500 ms.

For a longer message you have to display few toasts one after the other, or choose a different method to convey your message

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top