Android Toast.设置重力导致应用程序崩溃

标签 android debugging toast

我不明白为什么我的 toast 会使应用程序崩溃。

我有两套代码,一套是我最初编写的,但崩溃了,另一套是我发现可以工作的。

正在工作的人创建 toast 对象并同时声明文本。

Toast toast = 
Toast.makeText(QuizActivity.this,R.string.incorrect_toast, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

我所做的在上下文中创建对象,设置文本,然后设置重力并尝试显示它。

Toast toast = new Toast(QuizActivity.this);
toast.makeText(QuizActivity.this,
               R.string.correct_toast,
               Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

为什么这会使我的应用程序崩溃?

最佳答案

你的

Toast toast = new Toast(QuizActivity.this);

构造一个空的Toast对象。您必须先调用 setView(View),然后才能调用 show()。

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
            (ViewGroup) findViewById(R.id.custom_toast_container));

TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Android docs 中所述.

关于Android Toast.设置重力导致应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44193509/

相关文章:

android - Custom_toast 和 custom_toast_layout_id 未解析

android - Firebase getValue() 无法正确检索 boolean 值?

php - NetBeans + XDebug 断点不起作用

android - 如何在 Android 中为不同的内容使用相同的 Activity?

debugging - 在 Visual Studio Code 中为 Autohotkey 脚本设置断点

ios - 'NSInvalidArgumentException',原因 : '-[UISearchBar searchTextField]: unrecognized selector sent to instance

c# - Toast 不从 C# 中的控制台应用程序显示

javascript - 即使状态为 200,WNS 推送通知也不起作用

android - pubnub - 发布后备推送通知不起作用

Java 执行 'catch' block 没有错误,但不知何故仍然运行 'try' block