2

I have this code, where I define my own AlertDialog.Builder:

public class UnlockDialog extends AlertDialog.Builder {
    public UnlockDialog(Activity context) {
        super(context);

        LayoutInflater inflater = context.getLayoutInflater();
        View dlgView = inflater.inflate(R.layout.unlock_dialog, null); 
        setView(dlgView);
    }
}

the code works fine, but I get a warning on the inflater.inflate call:

Avoid passing null as the view root (needed to resolve layout parameters on the inflated layout's root element)

I had this issue as well in my adapters, where I could resolve it using providing a parent and false, as I found here: Avoid passing null as the view root (need to resolve layout parameters on the inflated layout's root element)

However, in the case above, I don't seem to have a parent available. I tried context.getParent(), but that didn't work.

Community
  • 1
  • 1
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • alertdialog builder is not really meant to be extended, imho – njzk2 Dec 02 '14 at 21:21
  • @njzk2 Possibly, but is that relevant to the question? `setView()` is still a public method in vanilla `AlertDialog.Builder`. – matiash Dec 02 '14 at 22:28
  • agreed, that was just a general comment. – njzk2 Dec 03 '14 at 00:28
  • @njzk2 thanks for that remark. I'll also look into doing it the "right" way. Any tips? – Bart Friederichs Dec 03 '14 at 08:05
  • `Builder`s follow, as the name suggest, the `Builder` pattern. The basic principle here is that all the calls can be chained, resulting in a compact and not so bulky code. Typically, if this builder is going to be user in several places, you could put it in a static helper method. Extending a class is more usually used for overriding behaviors, or mutualizing common behaviors. (in your case, it could make sense if a/ a lot of alerts are using the same view and b/ there is a little more to mutualize than just the content view) – njzk2 Dec 03 '14 at 14:18

1 Answers1

1

The warning should not apply in this case. The root parameter, when attachToRoot is false, is only used to call its generateDefaultLayoutParams() method and assign the resulting LayoutParams to the inflated view.

In this case, the dialog will overwrite them, so they would be unused anyway.

Please check this article, particularly the section Every Rule Has An Exception.

However, because the result will go into the dialog, which does not expose its root view (in fact, it doesn’t exist yet), we do not have access to the eventual parent of the layout, so we cannot use it for inflation. It turns out, this is irrelevant, because AlertDialog will erase any LayoutParams on the layout anyway and replace them with match_parent.

matiash
  • 54,791
  • 16
  • 125
  • 154