Android 中LayoutInflater的使用

本文深入探讨了Android开发中LayoutInflater的概念及其在获取布局文件对象和创建View实例方面的作用,提供了三种使用方法,并通过示例展示了如何在Activity中应用。

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);
 }
}

       Android里面想要创建一个画面的时候, 一般都是新建一个类, 继承Activity类, 然后在onCreate里面使用setContentView方法来载入一个在xml里定义好的界面.

其实在Activity里面就使用了LayoutInflater来载入界面, 通过getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法可以获得一个LayoutInflater, 然后使用inflate方法来载入layout的xml, 对于一个没有被载入或者想要动态载入的界面, 都需要使用inflate来载入.

对于一个已经载入的界面, 就可以使用这个界面调用findViewById方法来获得其中的子界面了.


另外getSystemService()是Android很重要的一个API,它是Activity的一个方法,根据传入的NAME来取得对应的Object,然后转换成相应的服务对象。以下介绍系统相应的服务。 

传入的Name返回的对象说明
WINDOW_SERVICEWindowManager管理打开的窗口程序
LAYOUT_INFLATER_SERVICELayoutInflater取得xml里定义的view
ACTIVITY_SERVICEActivityManager管理应用程序的系统状态
POWER_SERVICEPowerManger电源的服务
ALARM_SERVICEAlarmManager闹钟的服务
NOTIFICATION_SERVICENotificationManager状态栏的服务
KEYGUARD_SERVICEKeyguardManager键盘锁的服务
LOCATION_SERVICELocationManager位置的服务,如GPS
SEARCH_SERVICESearchManager搜索的服务
VEBRATOR_SERVICEVebrator手机震动的服务
CONNECTIVITY_SERVICEConnectivity网络连接的服务
WIFI_SERVICEWifiManagerWi-Fi服务
TELEPHONY_SERVICETeleponyManager电话服务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值