In the following example I have onCreateDialog
and showDialog
deprecated.
package com.dialogtest;
import android.app.Dialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CharSequence[] items = {"Google", "Apple", "Microsoft"};
// Declare the boolean array of same size as items
boolean[] itemsChecked = new boolean[items.length];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
showDialog(1);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 1:
return new AlertDialog.Builder(this)
//.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!" : " unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
).create();
}
return null;
}
}
I was suggested to use DialogFragment but I am not so sure.
So I want to know that is it not possible to directly use AlertDialog anymore?
As per reference docs AlertDialog is a subclass of Dialog that can display one, two or three buttons.
In your case use the below code :
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ExampleActivity.this);
//.setIcon(R.drawable.ic_launcher)
alertDialog.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(getBaseContext(),
"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
}
)
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
Toast.makeText(getBaseContext(),
items[which] + (isChecked ? " checked!" : " unchecked!"),
Toast.LENGTH_SHORT).show();
}
}
.show();
}