Abhishek Tandon Abhishek Tandon - 2 months ago 7
Android Question

Creating Alert Dialog box in Android and add a button to Dialog (popup) to close it

I am creating a About us screen as a popup/dialog in android. I want to add a button (OK or CANCEL) to this dialog. How can I do that ?

This is my layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/popup"
android:layout_height="wrap_content"
android:background="#E3C39D"
android:orientation="vertical"
android:padding="0dp">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="About Us.."
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="8dp"
android:textSize="20dp"
android:textColor="#ffffff"
style="@style/TextShadow"/>

<View
android:id="@+id/SplitLine_hor1"
android:layout_width="match_parent"
android:layout_height= "1dp"
android:background="#000" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="16dp"
android:text="Hello ! I want to put a button below with label 'OK' and Click on this OK button the popup should be close. Thank you !" />

</LinearLayout>


and below is the function for Dialog box

public void AboutUsDialog(){
final AlertDialog.Builder alert;
alert = new AlertDialog.Builder(this);
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.activity_about_us, null);
alert.setView(dialogView);
alert.show();

alert.setPositiveButton("OK",null);
//alert.setInverseBackgroundForced(true);
}


I am using
alert.setPositiveButton("OK",null);
or
alert.setInverseBackgroundForced(true);
. But I did not get any button displayed in dialog.

Now Dialog gets OFF when I touch anywhere on the screen. I want to close popup through OK button only.

Thanks in advance !

Output

enter image description here

Answer

Below is my code to add buttons.

public void AboutUsDialog() {
        final AlertDialog.Builder alert;
        alert = new AlertDialog.Builder(this);
        LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.activity_about_us, null);
        alert.setPositiveButton("OK", null);  //This is my Solution to this question(adding OK button)
        alert.setCancelable(false);
        alert.setInverseBackgroundForced(true);
        alert.setView(dialogView);
        alert.show();
        //alert.setInverseBackgroundForced(true);
    }