I would like to know how to create custom material dialog for my application. Specifically, I need to achieve something like this
I have been following old method like this way:
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Sample");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
However, I got null pointer exception while tapping the button
. Any tutorial will be also a great help for me.
Android App Development for Beginners This example demonstrate about how to make custom dialog in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
There are three kinds of lists available with the AlertDialog APIs: A traditional single-choice list. A persistent single-choice list (radio buttons) A persistent multiple-choice list (checkboxes)
Write a new class that extends to DialogFragment
.
public class CustomDialog extends DialogFragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_dialog,container,false);
getDialog().setTitle("Sample");
Button doneBtn = (Button) mView.findViewById(R.id.done_convert);
doneBtn.setOnClickListener(doneAction);
return view;
}
View.OnClickListener doneAction = new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Test",Toast.LENGTH_LONG).show();
}
};
}
Then call it from your activity
FragmentManager fm = getSupportFragmentManager();
CustomDialog custom = new CustomDialog();
custom.show(fm,"");
Hope, it will work.
I think you should make your own class which extends DialogFragment
public class YourDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom, null);
Button dialogButton = (Button) dialogView.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialogView);
return builder.create();
}
and in your activity use this code to show the dialog
YourDialog yourDialog = new YourDialog();
yourDialog.show(getFragmentManager(), "YOUR_DIALOG_TAG");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With