How to create a message box in Android

NewImage

This is a tutorial 3 on how to create your own android application series.  If you have not read the first article on how to create your first android application, follow this link. In this tutorial we will learn how to display message box or dialog box. Message box is created based on AlertDialog.Builder classes. This class will creates a builder for an alert dialog that uses the default alert dialog theme.  

Open the last project in Android Studio. We will add the following code in our MainActivity java.

NewImage

First we need to add the following classe

 

import android.app.AlertDialog;
import android.content.DialogInterface;

 

We also are going to initialize the AlerDialog object and set the properties and method.

 

 

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("This is a message box");

alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You Ok BUtton",Toast.LENGTH_LONG).show();
}
});



AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

 

 

NewImage

 

Full code to run messagebox in android. 

package androidrich.com.hellome;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("This is a message box");

alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You click Ok Button",Toast.LENGTH_LONG).show();
}
});



AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

No comments:

Post a Comment