您的位置:首页 > 移动开发 > Android开发

Android_LayoutInflater的作用与用法详解

2013-08-03 18:38 519 查看

1.LayoutInflater作用

加载界面,将需要加载的界面动态的加载!得到LayoutInflater的实例对象,在使用inflate方法将指定的界面填充!

2.得到LayoutInflater对象

//得到LayoutInflater对象的三种方式
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = this.getLayoutInflater();
LayoutInflater inflater = LayoutInflater.from(this);

3.加载界面

//Inflate(填充) a new view hierarchy(层级) from the specified xml resource. Throws InflateException if there is an error.
public View  inflate (int resource,		//ID for an XML layout resource to load
ViewGroup root) 	//Optional view to be the parent of the generated hierarchy. <span style="background-color: rgb(255, 255, 255);">
</span>

4.View指定宽高无效

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="300dp"
android:layout_height="80dp"
android:text="Button" >

</Button>


其实这里不管你将Button的layout_width和layout_height的值修改成多少,都不会有任何效果的,因为这两个值现在已经完全失去了作用。平时我们经常使用layout_width和layout_height来设置View的大小,并且一直都能正常工作,就好像这两个属性确实是用于设置View的大小的。而实际上则不然,它们其实是用于设置View在布局中的大小的,也就是说,首先View必须存在于一个布局中,之后如果将layout_width设置成match_parent表示让View的宽度填充满布局,如果设置成wrap_content表示让View的宽度刚好可以包含其内容,如果设置成具体的数值则View的宽度会变成相应的数值。这也是为什么这两个属性叫作layout_width和layout_height,而不是width和height。

再来看一下我们的button_layout.xml吧,很明显Button这个控件目前不存在于任何布局当中,所以layout_width和layout_height这两个属性理所当然没有任何作用。那么怎样修改才能让按钮的大小改变呢?解决方法其实有很多种,最简单的方式就是在Button的外面再嵌套一层布局,如下所示:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
android:layout_width="300dp"
android:layout_height="80dp"
android:text="Button" >
</Button>

</RelativeLayout>
看到这里,也许有些朋友心中会有一个巨大的疑惑。不对呀!平时在Activity中指定布局文件的时候,最外层的那个布局是可以指定大小的呀,layout_width和layout_height都是有作用的。确实,这主要是因为,在setContentView()方法中,Android会自动在布局文件的最外层再嵌套一个FrameLayout,所以layout_width和layout_height属性才会有效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: