Search code examples
androidandroid-layoutandroid-edittextpreferenceactivity

How to get elements(findViewById) for a layout which is dynamically loaded(setView) in a dialog?


I need to get the EditText that's defined in an xml layout which is dynamically loaded as a view in a preference dialog i.e. :

public class ReportBugPreference extends EditTextPreference {

    @Override
    protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
        super.onPrepareDialogBuilder(builder);   
        builder.setView(LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug_layout,null));
        EditText edttxtBugDesc = (EditText) findViewById(R.id.bug_description_edittext); // NOT WORKING
    }

}

EDIT : SOLUTION by jjnFord

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);  

    View viewBugReport = LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug,null);
    EditText edttxtBugDesc = (EditText) viewBugReport.findViewById(R.id.bug_description_edittext);

    builder.setView(viewBugReport);



}

Solution

  • Since you are extending EditTextPreference you can just use the getEditText() method to grab the default text view. However, since you are setting your own layout this probably won't do what you are looking for.

    In your case you should Inflate your XML layout into a View object, then find the editText in the view - then you can pass your view to the builder. Haven't tried this, but just looking at your code I would think this is possible.

    Something like this:

    View view = (View) LayoutInflater.from(ctx).inflate(R.layout.preference_report_bug_layout, null);
    EditText editText = view.findViewById(R.id.bug_description_edittext);
    builder.setView(view);