We have seen how to create and use Alert Dialog. Now we will see how to create and use a general dialog. In most places you find Alert Dialog explained on after they have given you a basic tutorial about Dialogs, their creation and use. However since Alert Dialog is a complete predefined element of Android, I chose to give you the tutorial earlier so that the learning curve for you remains smooth.
Here we will create a dialog, a layout for it and display it in an activity. Complete Source Code is at the bottom.
- Navigate to <yourpackagename> -> res -> layout.
- Create an XML, pick up a layout for it and name it according to your choice. We will use this layout for the dialog.
- I will just have a button and a text view in the dialog. You can follow along or you can become creative and add more elements. Write the following code in the dialog
- Now in the activity I have a button that triggers the dialog on the click. Add the following code to the onClick() method of the onClickListener() constructor.
[java]
final Dialog d = new Dialog(Main.this);
d.setContentView(R.layout.dialog);
Button tempbut = (Button) d.findViewById(R.id.button1);
tempbut.setOnClickListener(new OnClickListener() {@Override
public void onClick(View v) {
// TODO Auto-generated method stub
d.dismiss();
}
});
d.setTitle("Test Dialog");
d.show();
[/java] - Save it and execute it on the emulator/device.
This is how it looks on my Eclair emulator. Clicking the button will dismiss the dialog. This has been defined in the dialog code. Take some time to go through the code you have just added. It is very simple but nonetheless important.
COMPLETE SOURCE CODE
dialog.xml
activity_main.xml
MainActivity.java
[java]
package com.nero.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.but);
but.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final Dialog d = new Dialog(MainActivity.this);
d.setContentView(R.layout.dialog);
Button tempbut = (Button) d.findViewById(R.id.button1);
tempbut.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
d.dismiss();
}
});
d.setTitle("Test Dialog");
d.show();
}
});
}
}
[/java]