First, the layout file Part.xml:
Copy Code code as follows:
<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:paddingbottom= "@dimen/activity_vertical_margin"
android:paddingleft= "@dimen/activity_horizontal_margin"
android:paddingright= "@dimen/activity_horizontal_margin"
android:paddingtop= "@dimen/activity_vertical_margin"
Tools:context= ". Mainactivity ">
<button
Android:id= "@+id/button1"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:layout_margintop= "64DP"
android:text= "Add"/>
<edittext
Android:id= "@+id/edittext1"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:ems= "Ten" >
<requestfocus/>
</EditText>
</RelativeLayout>
Second, through the background code to generate the foreground layout:
Copy Code code as follows:
Package Com.example.codeui;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.content.Context;
Import Android.view.LayoutInflater;
Import Android.view.Menu;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.LinearLayout;
Import Android.widget.TextView;
public class Mainactivity extends activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
LinearLayout layout=new LinearLayout (this);
Layout.setorientation (linearlayout.vertical)//Show Direction
Add a View object to the layout interface
TextView TextView =new TextView (this);
Textview.settext ("Hello Code UI");
Viewgroup.layoutparams params = new Viewgroup.layoutparams (
Viewgroup.layoutparams.fill_parent,viewgroup.layoutparams.wrap_content);
Add to
Layout.addview (Textview,params);
To add a layout for an external XML definition
View view = Getpartview ();
Layout.addview (view);
Viewgroup.layoutparams layoutparams = new Viewgroup.layoutparams (
Viewgroup.layoutparams.fill_parent,viewgroup.layoutparams.fill_parent);
Setcontentview (layout, layoutparams);
Setcontentview (R.layout.activity_main);
Code-writing is highly efficient, but difficult to maintain
}
To add a view to a layout by loading an XML file
Public View Getpartview () {
Generate a View object from an XML layout file through the Layoutinflater
Layoutinflater Inflater = (layoutinflater) getsystemservice (Context.layout_inflater_service);
Mount the View object on that parent element, there is no null here
Return inflater.inflate (R.layout.part, NULL);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
}