我不明白为什么我的 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/