Android 界面Inflater

界面 Inflater

[功能]
android 提供了一个工具 能够把int 的 *.xml 文件转化为 View 这就是XxxInflater 主要有2种:
* LayoutInflater
* MenuInflater

[使用]
1. 得到 LayoutInflater & MenuInflater 的实例
 

Java代码 复制代码
  1. MenuInflater mInflater = getMenuInflater();   
  2. LayoutInflater lInflater = getLayoutInflater();  

MenuInflater mInflater = getMenuInflater();
LayoutInflater lInflater = getLayoutInflater();


(需要补充的是:上述二者仅在 Activity 中才有效!)

2. 如何使用

* MenuInflater  //比如现在有一个关于 menu 的 menu_item.xml 如下:
 

Java代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>     
  2. <menu xmlns:android="http://schemas.android.com/apk/res/android">     
  3.     <item      
  4.         android:id="@+id/Item_1"      
  5.         android:title="Item_1"  />     
  6.     <item      
  7.         android:id="@+id/Item_2"      
  8.         android:title="Item_2" />     
  9.     <item      
  10.         android:id="@+id/Item_3"      
  11.         android:title="Item_3"    
  12.         android:enabled="false"  />     
  13. </menu>  

<?xml version="1.0" encoding="utf-8"?>  
<menu xmlns:android="http://schemas.android.com/apk/res/android">  
    <item   
        android:id="@+id/Item_1"   
        android:title="Item_1"  />  
    <item   
        android:id="@+id/Item_2"   
        android:title="Item_2" />  
    <item   
        android:id="@+id/Item_3"   
        android:title="Item_3" 
        android:enabled="false"  />  
</menu>



现在把它转化为 View.
 

Java代码 复制代码
  1. public boolean onCreateOptionsMenu(Menu menu) {   
  2.         super.onCreateOptionsMenu(menu);    
  3.         MenuInflater mInflater = getMenuInflater();   
  4.   
  5.         mInflater.inflate(R.layout.menu_item, menu);   
  6.         return true;   
  7.     }  

public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu); 
    	MenuInflater mInflater = getMenuInflater();

    	mInflater.inflate(R.layout.menu_item, menu);
    	return true;
    }




LayoutInflater  // 和 MenuInflater 的使用基本类似 也是根据int 的 *.xml 文件得到 View 所不同的就是 嵌套原因 所以多了一个参数-ViewGroup 用来表示 父View 比如:在 LinearLayout layout 里面有一个 TextView 且其用tv.xml 描述 那么应该如下使用
 

Java代码 复制代码
  1. LayoutInflater iInflater = getLayoutInflater();   
  2. iInflater.inflate(R.layout.tv,layout);  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值