LayoutInflater的inflate方法学习

 

inflate 和setContentView 区别 

  1) inflate 只是加载xml到内存中,不会显示到窗口,如果需要显示需要调用 setContentView(view);,未显示之前可以调用相应的方法对View进行修改

  2) setContentView 如果调用了则View会直接显示到面板上 

  

  2 几个inflate方法的理解   

   1) view = getLayoutInflater().inflate(R.layout.activity_fragment31 ,null ); 

    虽然activity_fragment31的高度只有200dp但是显示的时候整个布局会显示到整个Activity ,因为ViewGroup root 为空 ,所以test视图会设置到activity上 ,则取得当前window的layoutparam赋值给test视图也就充满了屏幕,

  2) view = getLayoutInflater().inflate(R.layout.activity_fragment31, (ViewGroup) view,false ); 

  同上activity_fragment31会充满整个屏幕, 理由同上 

 

  3)view = getLayoutInflater().inflate(R.layout.activity_fragment31, (ViewGroup) view,true ); 

  这个activity_fragment31高度会显示为200dp ,test视图保存到了textView下面,并且保留了其自己的layoutparam参数

 

 三、方法中3个参数的理解

 

        resource:需要加载布局文件的id,意思是需要将这个布局文件中加载到Activity中来操作。   

root:需要附加到resource资源文件的根控件,什么意思呢,就是inflate()会返回一个View对象,

如果第三个参数attachToRoot为true,将xml挂在root上,将root作为根对象返回,

attachToRoot为false:root对象的LayoutParams属性附加到resource对象的根布局对象上,然后返回该xml

 

 1 先放上代码

public class Fragment3TestActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_fragment3,
                null);
        
//        view = getLayoutInflater().inflate(R.layout.activity_fragment31 ,null );
//        view = getLayoutInflater().inflate(R.layout.activity_fragment31, (ViewGroup) view,false );
        view = getLayoutInflater().inflate(R.layout.activity_fragment31, (ViewGroup) view,true );

        setContentView(view);
    }
  
}

 2 activity_fragment3.xml

<?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:background="#ff0000"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="hello world" />

</LinearLayout>

 3 activity_fragment31.xml

 

 

<?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="200dp"
    android:background="#ffffff00"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="test" />

</LinearLayout>

 

 

 

 

 

 

 

猜你喜欢

转载自username2.iteye.com/blog/2184050