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

Android基础之使用inflater来实现动态加载布局

2015-08-05 11:50 656 查看
一、动态加载与静态加载的区别

1、动态加载是一种优化,降低资源的耗费。偶尔,在布局中会有一些比较复杂但是又很少用到的控件。不管它是消息详情,进度条还是未完成的提示信息,你都可以直到真正需要的时候再加载他们,以降低你的内存消耗,提升渲染效率。

2、动态布局,也就是可以根据业务的需求改变界面。实际上就是用代码写出界面,代码量比较大。而且维护起来十分的繁琐。特别是一些界面空间比较多的时候。静态的布局,是通过xml来实现的,适用于页面比较固定的情况。但是维护起来比较方便。

二、使用inflater来实现动态加载布局

1、在Activity、Fragment等中可获取到getLayoutInflater()

LayoutInflater _inflater = getLayoutInflater();
View _view = _inflater.inflate(R.layout.activity_main, null);
setContentView(_view);


2、在Adapter中不能获取到getLayoutInflater(),通过上下文获取

LayoutInflater _inflater = LayoutInflater.from(mContext);
View view = _inflater.inflate(R.layout.activity_main, null);
setContentView(_view);


三、在布局中动态添加组件

1、例子1

// 1、获取根布局属性
FrameLayout _frameLayout = (FrameLayout) findViewById(R.id.flyt_main);

// 2、获取组件,设置组件属性
final Button _button = new Button(this);
_button.setText("跳转到TwoActivity");

// 3、在布局中添加组件,设置组件属性
_frameLayout.addView(_button,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);


2、例子2

// 1、获取根布局属性
FrameLayout _frameLayout = new FrameLayout(this);

// 2、获取组件,设置组件属性
final Button _button = new Button(this);
_button.setText("跳转到TwoActivity");

// 3、在布局中添加组件,设置组件属性
_frameLayout.addView(_button,LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);

// 4、调用Window.setContentView()加载界面
setContentView(_frameLayout);


3、例子3

protected void AppendMainBody(int pResID) {
// 1、获取根布局属性
LinearLayout _mainBody = (LinearLayout) findViewById(R.id.llyt_main_body);
// 2、获取组件,设置组件属性
View _view = LayoutInflater.from(this).inflate(pResID,null);
// 3、在布局中添加组件,设置组件属性
_mainBody.addView(_view, RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android