Multiple XML files are often used in Android, but Setcontentview (r.layout.main) used in mainactivity Load only the Main.xml file, other XML files are not loaded into the current view, when we want to use the control in other XML files is found to use the Findviewbyid () method without error, but the value of the control cannot be found to be null, and once the corresponding event is added to the control, a null pointer exception appears. The reason is that the control is not loaded into the current view.
Workaround: Two types of
1. Using the Include statement in Main.xml
<include layout= "@layout/x"/>
2. Use Layoutinflater to give a simple example
Two XML files Main.xml and X.xml
Main.xml
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_width= "Fill_parent" Android:layout_height= "Fill_parent" android:orientation= "vertical" > <TextView Android:id= "@+id/tv" Android:layout_width= "Fill_parent" Android:layout_height= "Wrap_content" Android:text= "@string/hello" /></LinearLayout>
X.xml
<?XML version= "1.0" encoding= "Utf-8"?><Relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_width= "Fill_parent" Android:layout_height= "Fill_parent" android:orientation= "vertical" > <Button Android:id= "@+id/bt" Android:layout_width= "Wrap_content" Android:layout_height= "Wrap_content" Android:layout_below= "@id/tv" /></Relativelayout>
Code in activity:
1 PackageLEEMO.E;2 3 4 Importandroid.app.Activity;5 ImportAndroid.os.Bundle;6 ImportAndroid.view.LayoutInflater;7 ImportAndroid.view.View;8 ImportAndroid.view.View.OnClickListener;9 ImportAndroid.widget.Button;Ten Importandroid.widget.LinearLayout; One ImportAndroid.widget.TextView; A ImportAndroid.widget.Toast; - - Public classEeeactivityextendsActivity { the /**Called when the activity is first created.*/ - @Override - Public voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.main); -TextView TV =(TextView) Findviewbyid (r.id.tv); +Tv.settext ("Content is a change")); A at -Layoutinflater layout= This. Getlayoutinflater (); -View View=layout.inflate (R.layout.x,NULL); -Linearlayout.layoutparams params =NewLinearlayout.layoutparams ( - LinearLayout.LayoutParams.FILL_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT); in Addcontentview (view,params); -Button BT =(Button) View.findviewbyid (R.ID.BT); toBt.settext ("Μã»÷îò"); +Bt.setonclicklistener (NewOnclicklistener () { - the @Override * Public voidOnClick (View v) { $ //TODO auto-generated Method StubPanax NotoginsengToast.maketext (eeeactivity. This, "button click", - toast.length_short). Show (); the } + }); A the } + -}
This can also achieve the same effect, but found a problem, the control position is not good control, left to the future ....
"Original" Use of multiple XML files for Android