有三种方法可以获取layoutinflater的实例:
LayoutInflater layout=this.getLayoutInflater();//method1
LayoutInflater layout=LayoutInflater.from(this);//mrthod2
this.getSystemService(this.LAYOUT_INFLATER_SERVICE);//method3
有2个布局:
<pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/myLayout2">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="这是主界面" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"
android:text="这是辅助界面" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/myImage"/>
</LinearLayout>
现在来测试一下LayoutInflater().inflate的几种用法
1.inflate(view, null)
LayoutInflater layout= (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);//method3
View myView=layout.inflate(R.layout.other,null);
<pre name="code" class="java">ImageView imageView= (ImageView) myView.findViewById(R.id.myImage);
imageView.setImageResource(R.drawable.a);
setContentView(myView);
现在来看一下结果:
2.inflate(view, root, false)
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_main2,
null);
LayoutInflater layout= (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View myView=layout.inflate(R.layout.other, (ViewGroup) view,false);
ImageView imageView= (ImageView) myView.findViewById(R.id.myImage);
imageView.setImageResource(R.drawable.a);
setContentView(myView);
3.inflate(view, root, true)
View view = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_main2,
null);
LayoutInflater layout= (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View myView=layout.inflate(R.layout.other, (ViewGroup) view,true);
ImageView imageView= (ImageView) myView.findViewById(R.id.myImage);
imageView.setImageResource(R.drawable.a);
setContentView(myView);
结论:
如果不指定root参数,那么我们在把视图加载到Activity的时候,视图上的尺寸设置是没有效果的,直接会充满屏幕显示,
如果指定了root参数,但是第三个参数设置为false的时候,不会加载root视图,但是当前的布局文件中layoutparam参数会保存
如果第三个参数设置为true的时候,当前的布局会套在root布局里边,然后作为一个整体显示,并且layoutparam参数也是会保留的
以上是本人做的一些小测试,如有错误,还请指正...