Reputation: 201
So I am using a xml layout with a Textview to create a custom toast message. Everything works fine except for the custom duration for it. I know that I can set it to either LENGTH_SHORT or LENGTH_LONG, but I want it display longer than LENGTH_LONG. I've been working on figuring this out for hours and I am not sure what I am doing wrong. Basically, I want to set it for how many seconds my custom toast appears on the screen and then it disappears until the toast is called again each time. Here is what I have in my Main Java class...
public class MainActivity extends AppCompatActivity {
Button b;
TextView tv;
Toast myToast;
Handler h;
Runnable r;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.my_toast_button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myCustomToast(getApplicationContext(), "Hello World!");
}
});
}
private void myCustomToast(final Context context, final String toastMessage) {
LayoutInflater layoutInflater = getLayoutInflater();
final View customToastLayout = layoutInflater.inflate(R.layout.my_custom_toast, (ViewGroup) findViewById(R.id.container));
h = new Handler();
r = new Runnable() {
@Override
public void run() {
tv = customToastLayout.findViewById(R.id.my_custom_toast_tv);
tv.setText(toastMessage);
myToast = new Toast(context);
myToast.setView(customToastLayout);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.show();
myCustomToast(context, toastMessage);
}
};
h.postDelayed(r, 10000);
}
}
Thanks!
Upvotes: 2
Views: 5356
Reputation: 965
You can achieve it like this
private Toast mToastToShow;
public void showToast(View view) {
// Set the toast and duration
int toastDurationInMilliSeconds = 10000;
mToastToShow = Toast.makeText(this, "Hello world, I am a toast.", Toast.LENGTH_LONG);
// Set the countdown to display the toast
CountDownTimer toastCountDown;
toastCountDown = new CountDownTimer(toastDurationInMilliSeconds, 1000 /*Tick duration*/) {
public void onTick(long millisUntilFinished) {
mToastToShow.show();
}
public void onFinish() {
mToastToShow.cancel();
}
};
// Show the toast and starts the countdown
mToastToShow.show();
toastCountDown.start();
}
You can set it to your custom view
Upvotes: 1
Reputation: 70
Instead of using Toast.LENGTH_LONG or Toast.LENGTH_SHORT, just enter an int, it's looking for an int. I believe it's in milliseconds, so if you use 1000, it would be 1000 milliseconds
Upvotes: 1