Reputation: 95
I am new in android and I have tried to write a class MyAlertDialog
for alert dialog to use it every where I need an alert dialog. I have written a method showAlertDialog
in the class to do this. I found that the method have to be static. Could anybody tell me why it should be static? Here is my code:
public class MyAlertDialog extends AppCompatActivity {
public static void alertDialogShow(Context context, String message) {
final Dialog dialog;
TextView txtAlertMsg;
TextView txtAlertOk;
dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_my_alert_dialog);
txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
txtAlertMsg.setText(message);
txtAlertOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
and I have called it like bellow:
MyAlertDialog.alertDialogShow(MainActivity.this,"Here is my message");
Upvotes: 1
Views: 71
Reputation: 939
Why it should be static?
For memory management
How?
Declaring a field static means only one instance of it will exists
It does not belong to a specific instance, they can't refer to instance members, meaning they belong to the class itself
Upvotes: 2
Reputation: 1485
It is not necessary to be static
You can also do it the non-static way:
public class MyAlertDialog {
private Context context;
private String message;
public MyAlertDialog(Context context,String message){
this.context = context;
this.message = message;
}
public void alertDialogShow() {
final Dialog dialog;
TextView txtAlertMsg;
TextView txtAlertOk;
dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_my_alert_dialog);
txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
txtAlertMsg.setText(message);
txtAlertOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
To call it:
MyAlertDialog myAlertDialog = new MyAlertDialog(MainActivity.this,"Here is my message");
myAlertDialog.alertDialogShow();
Upvotes: 0