Question

From the official documentation:

A subclass of Dialog that can display one, two or three buttons. If you only want to display a String in this dialog box, use the setMessage() method. If you want to display a more complex view, look up the FrameLayout called "custom" and add your view to it:

 FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
 fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));

But the problem is that android.R.id.custom presents only in OS from 8 API Level.

How can I make custom AlertDialog if I work with less API Level?

Was it helpful?

Solution

actually what you do is as follows:

first, you create the custom_layout.xml under res/layout. then you'll add the next code to your activity

Dialog myDialog = new Dialog(this);
myDialog .setOwnerActivity(MyParentActivity.this);
myDialog .setContentView(R.layout.custom_layout);
myDialog .setTitle("title");

and you can show and dismiss it usingmyDialog.show(); and myDialog.dismiss();

if you have buttons or other views inside your custom_layout.xml, you can find them by

Button myButton = (Button) myDialog.findViewById(R.id.myButton);

I hope this helps.

OTHER TIPS

For displaying tooltips in an app I'm working on, I created a new class that extends Dialog, and used setContentView() to display my custom layout. Depending on your needs (you didn't say exactly why it had to be an AlertDialog), this may work for you as well.

This may be somewhat subjective, but in order to save some sanity, you might want to take current Android version distribution into account when picking a target API. According to the following platform distribution, only 10.2% of Android devices use an API level below 8, with just about 86% using API levels 8-10.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top