I have decided to write my own Utility class for Toast to cut repetitive code
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();
}
}
}
As you can see there are two methods. I want to avoid of initializing of stacked toasts, that's way I cancel the old toast before the new one. In my client-classes I'm using it like that:
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");
}
});
}
}
When I click on button multiple times I'm getting stacked toasts - previous toasts are not being destroyed. So I need a help to define why it behaves in this way.
UPDATE Earlier I wrote the toast-code inside activity class and it worked perfectly. For example:
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();
}
}