Android 中LayoutInflater的使用

LayoutInflater在Android中是“扩展”的意思,作用类似于findViewById(),不同的是LayoutInflater是用来获得布局文件对象的,而 findViewById()是用来获得具体控件的。LayoutInflater经常在BaseAdapter的getView方法中用到,用来获取整个View并返回。

LayoutInflate 的三种用法:

方法一:
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);

方法二:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);

方法三:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);

 

简单示例:

public class LayoutInflaterActivity extends Activity {
private EditText et;
private Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 第一种方法
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
// 第二种方法
// LayoutInflater inflater = getLayoutInflater();
// View layout = inflater.inflate(R.layout.main, null);
// 第三种方法
// LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
// View layout = inflater.inflate(R.layout.main, null);
// 获取具体控件并实例化
et = (EditText) layout.findViewById(R.id.edittext);
et.setBackgroundColor(Color.YELLOW);
btn = (Button) layout.findViewById(R.id.btn);
btn.setBackgroundColor(Color.CYAN);
// 显示
setContentView(layout);
}
}

需要注意的是在获取控件时,要指明属于哪一个layout。

一般像我们初始化Button时,是Button btn=(Button)findViewById(R.id.button1);

其实完整的写法应该是

Button btn=(Button)this.findViewById(R.id.button1);

但是在onCreate里面,this可以省略。

在自定义的界面加载时,需要这样写:

EditText et=(EditText)layout.findViewById(R.id.tv_setIp);(layout为你加载的EditText所存在的布局)

而且要在setView之后初始化。

代码片段:

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(layout);
et_setIP = (EditText) layout.findViewById(R.id.et_setIP);

 

另外getSystemService()是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。 
传入的Name 返回的对象 说明
WINDOW_SERVICE WindowManager 管理打开的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定义的view
ACTIVITY_SERVICE ActivityManager 管理应用程序的系统状态
POWER_SERVICE PowerManger 电源的服务
ALARM_SERVICE AlarmManager 闹钟的服务
NOTIFICATION_SERVICE NotificationManager 状态栏的服务
KEYGUARD_SERVICE KeyguardManager 键盘锁的服务
LOCATION_SERVICE LocationManager 位置的服务,如GPS
SEARCH_SERVICE SearchManager 搜索的服务
VEBRATOR_SERVICE Vebrator 手机震动的服务
CONNECTIVITY_SERVICE Connectivity 网络连接的服务
WIFI_SERVICE WifiManager Wi-Fi服务
TELEPHONY_SERVICE TeleponyManager 电话服务

 

参考文献:http://hi.baidu.com/laocui172/item/03649bfcaee761c4a835a2ac

posted @ 2014-06-05 22:38  银色的流星  阅读(283)  评论(0)    收藏  举报