I'm working on a project and I've noticed that I need to copy and paste the same custom methods in almost all my scripts. Is it wrong what I'm doing? I'm duplicating it over and over. Any help is much appreciated.
Sample:
Answer:
Sample:
/********************************************************************
* SHORTENED TOAST *
*********************************************************************/
public void showToast(String value){
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
/********************************************************************
* SHORTENED ALERTDIALOG *
*********************************************************************/
public void showAlert(String title, String btn_txt, String message){
final AlertDialog.Builder alert = new AlertDialog.Builder(EventHome.this);
alert.setTitle(title).setMessage(message)
.setNeutralButton(btn_txt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alert.setCancelable(true);
}}).show();
}
Answer:
Create a helper class (lets say Helper) and move all your repetitive methods in that class file with access modifier as
public static
. Doing so will allow you to call the methods together with class name as prefix. See below:public class Helper{
/********************************************************************
* SHORTENED TOAST *
*********************************************************************/
public static void showToast(Context context, String value){
Toast.makeText(context, value, Toast.LENGTH_SHORT).show();
}
}
now call the following in your activities when you want to show toast:
Helper.showToast(this, "hello world!");
No comments:
Post a Comment