Articles‎ > ‎Android Articles‎ > ‎

Custom Dialog Box Popup using Layout in Android

posted Jan 25, 2011, 4:38 AM by thiyagaraaj Mr   [ updated Aug 20, 2011, 4:38 AM ]

Main XML Code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/ClkBtn"
android:text="Click Me. and Get Dialog"></Button>
</RelativeLayout>

Custom Dialog XML Layout

create mydialog.xml in Layout folder.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:background="#000080"
 android:layout_width="250px"
 android:layout_height="wrap_content">
  
 <TextView android:id="@+id/Tv1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textSize="20px"
 android:text="Articles"/>
 
 <TextView android:id="@+id/Tv2"
 android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:textSize="14px"
 android:layout_below="@+id/Tv1"
 android:text="More Android Articles visit\nhttp://i.thiyagaraaj.com"/>
 
 <Button android:id="@+id/Btn1"
 android:layout_below="@+id/Tv2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:text="Close" />
</RelativeLayout>

Java Code:

Add this java code in your activity java file.( change your class name :ExPopup )

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ExPopup extends Activity {
Dialog myDialog;
Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button) findViewById(R.id.ClkBtn);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
myDialog = new Dialog(ExPopup.this);
myDialog.setContentView(R.layout.mydialog);
myDialog.setTitle("My Dialog");
myDialog.setCancelable(true);
Button button = (Button) myDialog.findViewById(R.id.Btn1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.show();
}
});
}
}

Screenshot:

Download example code: