Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);



}
like image 970
Vikas Singh Avatar asked Apr 25 '12 10:04

Vikas Singh


People also ask

What is FindViewById () method used for?

FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .

What is Viewview FindViewById?

view. findViewById() is used to find a view inside a specific other view. For example to find a view inside your ListView row layout.


2 Answers

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);
like image 184
jjNford Avatar answered Oct 16 '22 21:10

jjNford


LayoutInflater is needed to create (or fill) View based on XML file in runtime. For example if you need to generate views dynamically for your ListView items. What is the layout inflater in an Android application?

  1. Create your LayoutInflater:

LayoutInflater inflater = getActivity().getLayoutInflater();

  1. Create your view by inflater refered to your_xml_file:

View view= inflater.inflate(R.layout.your_xml_file, null);

  1. Find your object in your layout by id.

TextView textView = (TextView)view.findViewById(R.id.text_view_id_in_your_xml_file);

  1. Use your object: i.e.

textView.setText("Hello!");

like image 29
Sara Avatar answered Oct 16 '22 22:10

Sara