custom dialog in android

Showing posts with label custom dialog in android. Show all posts
Showing posts with label custom dialog in android. Show all posts

Tuesday, August 5, 2014

Creating custom dialog using xml.....


This tutorial show you how to create a custom dialog in Android.
          1-  Create activity & custom dialog layout xml file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press me!" />

</LinearLayout>


custom_dialog.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hey! I'm Dialog."
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <Button
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press Me!" />


</LinearLayout>


2-  Create Activity Class.

MainActivity.java

package com.example.customdialog;

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 MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showCustomDialog();
}
});
}

protected void showCustomDialog() {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(this);
dialog.setTitle("Custom Dialog");
dialog.setContentView(R.layout.custom_dialog);
Button button = (Button) dialog.findViewById(R.id.but);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}

}