This question already has an answer here:
-
How do I display an alert dialog on Android?
27 answers
I need to show a little text message to the users that clicks a button on my Android app, on IOS I just had to create an AlertView that it's simple to use but with Android i'm struggling because the solution seems x10 times harder. I saw that I need to use a DialogFragment but I can't understand how to make it work, can someone explain? Also, is my solution right or there is something easier to show a simple text message to users?
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
No my friend its very simple, try using this:
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.
You can easily make your own 'AlertView' and use it everywhere.
alertView("You really want this?");
Implement it once:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialoginterface, int i) {
// dialoginterface.cancel();
// }})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}