欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LayoutInflater

程序员文章站 2024-02-10 23:48:46
...

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