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:
public class EventHome extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
/********************************************************************
* 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();
}
}
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:now call the following in your activities when you want to show toast: