码迷,mamicode.com
首页 > 移动开发 > 详细

Android--addView()和setView()

时间:2015-10-04 22:16:37      阅读:414      评论:0      收藏:0      [点我收藏+]

标签:

我们在添加视图文件的时候有两种方式,一种是通过在xml文件定义layout,另一种方式是在java代码中动态生成布局文件。

在xml中定义的layout要想转化为view,需要使用到LayoutInflater类。

1.构造xml文件

2.LayoutInflater

提到addview,首先要了解一下LayoutInflater类。这个类最主要的功能就是实现将xml表述的layout转化为View的功能。为了便于理解,我们可以将它与findViewById()作一比较,二者都是实例化某一对象,不同的是findViewById()是找xml布局文件下的具体widget控件实例化,而LayoutInflater找res/layout/下的xml布局文件来实例化的。

(1)创建

LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);或

LayoutInflater inflater = LayoutInflater.from(Activity.this);或

LayoutInflater inflater = getLayoutInflater();

这三种方法本质是相同的。

(2)inflate()

用LayoutInflater.inflate() 将LayOut文件转化成VIew。

View view = inflater.inflate(R.layout.login, null);

 

3.添加视图文件

举个例子,假如定义了一个toast,则可以设置视图文件

toast.setView(view);

====

现在给出一个常用的土司烤面包的例子--让带图片和文本的面包居中显示,看代码:

其中主文件只放置了一个button,xml文件就不赘述。

Android--addView()和setView()

标签:

原文地址:http://www.cnblogs.com/zrui513/p/4854991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!