In android, LayoutInflater is a bit similar to the findViewById (id) of the Activity. The difference is that LayoutInflater is used to find the xml layout file in layout and instantiate it! FindViewById () is used to find the widget controls (such as buttons and TextView) in a specific xml file ).
The following is an example:
1. In the res/layout folder, add an xml file dialog. xml
Copy codeThe Code is as follows: <LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "horizontal">
<ImageView
Android: id = "@ + id/diaimage"
Android: layout_width = "wrap_content"
Android: layout_height = "fill_parent">
</ImageView>
<TextView
Android: id = "@ + id/diatv"
Android: layout_width = "wrap_content"
Android: layout_height = "fill_parent"/>
</LinearLayout>
2. Add a button to the main. xml file to display a Dialog.
Copy codeThe Code is as follows: <Button
Android: id = "@ + id/btnshowdialog"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "Show Dialog"/>
3. Add the following code to the onCreate method of MainActivity to implement specific function operations.
Copy codeThe Code is as follows: Button showdialog = (Button) findViewById (R. id. btnshowdialog );
Showdialog. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
AlertDialog. Builder builder = new AlertDialog. Builder (MainActivity. this );
AlertDialog dialog;
LayoutInflater inflater = getLayoutInflater ();
View layout = inflater. inflate (R. layout. dialog, null );
TextView diatv = (TextView) layout. findViewById (R. id. diatv );
Diatv. setText ("Welcome to LayoutInflater study ");
ImageView image = (ImageView) layout. findViewById (R. id. diaimage );
Image. setImageResource (R. drawable. ic_launcher );
Builder. setView (layout); // <-- important, set the View of the dialog box content
Dialog = builder. create ();
Dialog. show ();
}
});
Run the program and click the button to achieve the following results!