问题
in my application i use a custom toast in almost all the activity. To create the custom toast i have the following method :
private void getCustomToast(String message)
{
LayoutInflater li = getLayoutInflater();
View toastlayout = li.inflate(R.layout.toast_error, (ViewGroup)findViewById(R.id.toast_layout));
TextView text = (TextView) toastlayout.findViewById(R.id.toast_text);
text.setText(message);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastlayout);
toast.show();
}
It works fine but for each activity I need to duplicate this method, not really respectfull of the DRY principle ...
How can i make a static class (for example) in which i have a method which gonna fire the custom toast on the current activity ?
Thanks
回答1:
You should make a custom abstract Activity that contains the toast method, and then extend that for your application's activities:
public abstract class ToastActivity extends Activity {
protected void getCustomToast(String message)
{
LayoutInflater li = getLayoutInflater();
View toastlayout = li.inflate(
R.layout.toast_error,
(ViewGroup) findViewById(R.id.toast_layout));
TextView text = (TextView) toastlayout.findViewById(R.id.toast_text);
text.setText(message);
Toast toast = new Toast(this);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastlayout);
toast.show();
}
}
回答2:
I want to say you can create a [static] class which will accept a Context object. Then use:
Toast toast = Toast.makeText(context, text, duration).show();
So in your static class:
public static class Utility
{
public static void toast(Context context, String msg)
{
Toast toast = Toast.makeText(context, msg, Toast.DURATION_LONG).show();
}
}
Or something like that
来源:https://stackoverflow.com/questions/7041475/how-to-centralize-a-custom-toast-creation