Java 如何设置自定义Toast消息的自定义持续时间?
因此,我使用带有Textview的xml布局来创建自定义toast消息。除了自定义的持续时间外,其他一切都可以正常工作。我知道我可以将其设置为LENGTH\u SHORT或LENGTH\u LONG,但我希望它显示的长度大于LENGTH\u LONG。我花了好几个小时才弄明白这一点,但我不确定自己做错了什么。基本上,我想设置我的自定义toast在屏幕上出现的秒数,然后它消失,直到每次再次调用toast为止。下面是我的主Java类中的内容Java 如何设置自定义Toast消息的自定义持续时间?,java,android,toast,Java,Android,Toast,因此,我使用带有Textview的xml布局来创建自定义toast消息。除了自定义的持续时间外,其他一切都可以正常工作。我知道我可以将其设置为LENGTH\u SHORT或LENGTH\u LONG,但我希望它显示的长度大于LENGTH\u LONG。我花了好几个小时才弄明白这一点,但我不确定自己做错了什么。基本上,我想设置我的自定义toast在屏幕上出现的秒数,然后它消失,直到每次再次调用toast为止。下面是我的主Java类中的内容 public class MainActivity ext
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);
}
}
谢谢 不用Toast.LENGTH\u LONG或Toast.LENGTH\u SHORT,只需输入一个int,它正在寻找一个int。我相信它是以毫秒为单位的,所以如果使用1000,它将是1000毫秒
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();
}
您可以将其设置为自定义视图这可能适用于某些版本的操作系统,但其未记录的行为。setDuration的记录行为是,它需要很长或很短的时间,而不是很多MST。感谢您的回复CCT。我试过我的吐司。设置持续时间(1000);就像你说的。但是,我在1000下得到了一条红线,这是它给我的消息。“必须是:Toast.LENGTH\u SHORT,Toast.LENGTH\u LONG less…(Ctrl+F1)检查信息:确保当方法中的参数只允许一组特定的常量时,调用遵守这些规则。问题id:ErrorConstant”除了长或短之外,没有文档化的API可以显示任何长度的吐司。在Android的特定版本上可能会有一些bug/黑客,但一般来说没有任何东西能起作用。如果你要复制和粘贴别人的代码,至少要归功于作者辛迪·波文(Cindy Potvin)。