利用View.inflate加载xml

Layout1.xml

  xmlns:android="http://schemas.android.com/apk/res/android"

  android:orientation="vertical"

  android:layout_width="fill_parent"

  android:layout_height="fill_parent" >

  
    android:layout_width="fill_parent"

    android:layout_height="40px"

    android:background="#ff00ff00"

   android:text="This is main layout" />
 
android:id="@+id/box_1"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:layout_below="@+id/box_0">




Layout2.xml


android:id="@+id/box"

android:orientation="horizontal"

android:layout_width="fill_parent"

android:layout_height="fill_parent"  >

android:layout_width="fill_parent"
android:layout_height="40px"
android:background="#ffff0000"
android:text="this is 2" />


  setContentView(R.layout.layout_1);
        LinearLayout ll = (LinearLayout) findViewById(R.id.box_1);

        View vv = View.inflate(this, R.layout.layout_2, null);

        ll.addView(vv, new LinearLayout.LayoutParams( ll.getLayoutParams().width,ll.getLayoutParams().height));

这个主要是在某一个控件里面动态加载。

也可以利用inflate加载menu



android:title="Home"
android:icon="@drawable/home" >


android:title="Help"
android:icon="@drawable/help" >


android:title="Save n Quit"
android:icon="@drawable/save_quit" >


android:title="Quit"
android:icon="@drawable/exit" >




public class Welcome extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
// TODO
break;
case R.id.help:
// TODO
break;
case R.id.save:
// TODO
break;
case R.id.exit:
// TODO
break;
}
return true;
}
}

 

2.两种刚方法:

 LayoutInflater inflater = getLayoutInflater();
       
View layout = inflater.inflate(R.layout.toast_sms,
                                       
(ViewGroup) findViewById(R.id.toast_sms_root));

LayoutInflater mInflater = LayoutInflater.from(context);
View myView = mInflater.inflate(R.layout.customToast, null);
TextView sender = (TextView) myView.findViewById(R.id.sender);
TextView message = (TextView) myView.findViewById(R.id.message);

 

你可能感兴趣的:(android)