自定义LayoutInflater.Factory

转自:http://www.cnblogs.com/xitang/archive/2014/02/19/3556630.html


自定义LayoutInflater.Factory

自定义实现个Factory,可以用来解析自定义的属性。
public interface Factory {
        /**
         * Hook you can supply that is called when inflating from a LayoutInflater.
         * You can use this to customize the tag names available in your XML
         * layout files.
         * 
         * <p>
         * Note that it is good practice to prefix these custom names with your
         * package (i.e., com.coolcompany.apps) to avoid conflicts with system
         * names.
         * 
         * @param name Tag name to be inflated.
         * @param context The context the view is being created in.
         * @param attrs Inflation attributes as specified in XML file.
         * 
         * @return View Newly created view. Return null for the default
         *         behavior.如果返回一个view, 那么就会直接加入到原有View树中去。 如果返回null,则会走原来类似于onCreate的方法。
         */
        public View onCreateView(String name, Context context, AttributeSet attrs);
    }

protected void setBackGround() {
  getLayoutInflater().setFactory(
    new android.view.LayoutInflater.Factory() {
  
     @Override
     public View onCreateView(String name, Context context,
       AttributeSet attrs) {
      // TODO Auto-generated method stub
      // 指定自定义inflater的对象
      if (name
        .equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
       try {
        LayoutInflater inflater = getLayoutInflater();
        final View view = inflater.createView(name,
          null, attrs);
        new Handler().post(new Runnable() {
         public void run() {
          view
            .setBackgroundResource(R.drawable.application_background_static);
         }
        });
        return view;
       } catch (InflateException e) {
        e.printStackTrace();
       } catch (ClassNotFoundException e) {
        e.printStackTrace();
       }
      }
      return null;
     }
    });
 }



LayoutInflater.Factory这个值设置到LayoutInflater中,而LayoutInflater的获得又是跟谁Context而来的。也就是说相同的Context有着相同的LayoutInflater,那就可以重用相同的LayoutInflater.factory

 在BaseActivity中加入自己的Factory

     mLayoutMode = new BDLayoutMode(); // 针对该Activity的一些存储
        mLayoutInflateFactory = new BDLayoutInflateFactory(); //自定义的LayoutInflateFactory
        mLayoutInflateFactory.setViewMode(mLayoutMode);
        getLayoutInflater().setFactory(mLayoutInflateFactory); //  给该Activitry设置factory

这样在BDLayoutInflateFactory中就可以自定义解析自己关心的值了。

在BaseActivity的OnResume中开始,遍历每一个控件。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值