LayoutInflater

Android一分钟

  • 作用:把xml类型的布局转化成相应的View对象

    1. LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
    2. LayoutInflater inflater = LayoutInflater.from(context);
    3. LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  • inflater.inflater

    • inflate(int resource, ViewGroup root, boolean attachToRoot)
      
    • inflate(int resource, ViewGroup root)//attachToRoot = true
      
    • If attachToRoot is set to true, then the layout file specified in the first parameter is inflated and attached to the ViewGroup specified in the second parameter.

      • 如果attachToRoot=true,view对象将直接绑定到ViewGroup
    • When attachToRoot is false, the layout file from the first parameter is inflated and returned as a View.

      • 如果attachToRoot=false,view对象将被填充并且返回该对象,但是不会绑定到ViewGroup上,需要手动addView()绑定
    • attachToRoot 必须设置为 false的情况,例如:

      • recyclerview

        • public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
              LayoutInflater inflater = LayoutInflater.from(getActivity());
              View view = inflater.inflate(android.R.layout.list_item_recyclerView, parent, false);
              return new ViewHolder(view);
          }
          
        • 由于recyclerview会负责填充和绑带viewholder

      • Fragment

        • 由于FragmentManager负责add, remove and replace Fragments

          public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup, Bundle savedInstanceState) {
              View view = inflater.inflate(R.layout.fragment_layout, parentViewGroup, false);
              return view;
          }
          
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容