[学习笔记-Android]动态添加Layout-XML方式

来源:互联网 发布:socket客户端发送数据 编辑:程序博客网 时间:2024/05/17 03:23

LayoutInflater

Class Overview
Instantiates a layout XML file into its corresponding View objects.
在自身的页面中实例化一个XML文件配置的Layout
It is never used directly.
它从未被直接使用过
Instead, use two ways to retrieve a standard LayoutInflater instance
取而代之的用两种方式检索一个标准的LayoutInflater实例
that is already hooked up to the current context
已经连接到上下文
and correctly configured for the device you are running on.
并为你正在运行的设备正确地配置了

·getLayoutInflater( )
·getSystemService(Class)

以上是LayoutInflater在帮助文档中的类预览,那么如何使用这个类将我们已经配置好的XML在已有的界面中以Layout的形式添加进来呢?

public class MainView extends AppCompatActivity{    //声明一个上下文    private Context mContext;    //声明一个根布局    protected LinearLayout linearLayout;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //设置上下文引用        mContext = this;        init();    }    public void init(){        //根布局实例化        linearLayout= (LinearLayout) findViewById(R.id.mainActLayout);        //将XML配置好的Layout填充进一个新的View        LayoutInflater inflater = LayoutInflater.from(mContext);        //inflater()返回值为View类型        View view = inflater.inflater(R.Layout.activity_main_view,null);        //将View加入根布局中        linearLayout.addview(view);    }}

这样就可以将一个自定义的XML布局文件添加进生在运行的界面了。

学习自:
ICQ我的应用我做主-Android在布局中动态添加view的两种方法
原文链接
本篇只对自己使用的其中一种进行了记录

0 0
原创粉丝点击