所以我将XML布局与Textview一起使用来创建自定义的Toast消息。除了自定义的持续时间以外,其他一切都正常。我知道我可以将其设置为LENGTH_SHORT或LENGTH_LONG,但是我希望它的显示时间长于LENGTH_LONG。我已经花了好几个小时来解决这个问题,但不确定自己做错了什么。基本上,我想将其设置为我的自定义吐司出现在屏幕上多少秒,然后消失,直到每次再次调用吐司为止。这是我的主要Java类中的内容...
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);
}
}
谢谢!
答案 0 :(得分:1)
您可以这样实现
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();
}
您可以将其设置为自定义视图
答案 1 :(得分:0)
只需输入一个int即可,而不是使用Toast.LENGTH_LONG或Toast.LENGTH_SHORT。我相信是以毫秒为单位,所以如果您使用1000,那将是1000毫秒