【发布时间】:2018-05-18 05:58:33
【问题描述】:
我决定为 Toast 编写自己的实用程序类来减少重复代码
public class Utilities {
public static void initializeToast(Context context, Toast toast, String res) {
cancelToast(toast);
toast = Toast.makeText(context, res, Toast.LENGTH_SHORT);
toast.show();
}
public static void cancelToast(Toast toast){
if (toast != null) {
toast.cancel();
}
}
}
如您所见,有两种方法。我想避免初始化堆叠的吐司,这就是我在新吐司之前取消旧吐司的方式。在我的客户端类中,我是这样使用它的:
public class AddGroupActivity extends AppCompatActivity {
private EditText mEditWordView;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_group);
mEditWordView = findViewById(R.id.editText);
final Button button = findViewById(R.id.add_group_button);
button.setOnClickListener(view -> {
if (TextUtils.isEmpty(mEditWordView.getText())) {
Utilities.initializeToast(this, toast, "Message Example");
}
});
}
}
当我多次单击按钮时,我得到了堆积的 toast - 以前的 toast 没有被破坏。所以我需要帮助来定义它为什么会这样。
更新 早些时候,我在活动类中编写了 toast 代码,它运行良好。例如:
public class AddGroupActivity extends AppCompatActivity {
private EditText mEditWordView;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_group);
mEditWordView = findViewById(R.id.editText);
final Button button = findViewById(R.id.add_group_button);
button.setOnClickListener(view -> {
if (TextUtils.isEmpty(mEditWordView.getText())) {
initToast("Message");
}
});
}
private void cancelToast() {
if (toast != null) {
toast.cancel();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
cancelToast();
}
private void initToast(String res) {
cancelToast();
toast = Toast.makeText(this, res, Toast.LENGTH_SHORT);
toast.show();
}
}
【问题讨论】:
-
写一个条件来检查toast是否为空,然后尝试取消它。
-
toast.cancel();和 toast.hide();对清除所有堆叠的吐司没有用。
-
你永远不会初始化你的
private Toast toast;。它总是 null ,这就是为什么它不会取消任何东西 -
为什么不呢? toast = Toast.makeText(context, res, Toast.LENGTH_SHORT);没有初始化?
标签: android toast utility-method