我有什么理由不能坚持使用onCreateView的LayoutInflater吗?

时间:2013-12-30 22:47:47

标签: android android-fragments layout-inflater

我意识到在这种情况下,惯用法是将Context传递给CustomAdapter构造函数,并用它创建LayoutInflater。但我想知道下面的代码是否有任何问题。

public class MyFragment extends Fragment {

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
      this.inflater = inflater;

      MyLayout layout = (MyLayout) inflater.inflate(R.layout.layout);
      SomeAdapterView adapterView  = (SomeAdapterView) layout.findViewById(R.id.adapterView);
      CustomAdapter adapter = new CustomAdapter(inflater);
      adapterView.setAdapter(adapter);

      return layout;
   }   


   private class CustomAdapter extends WhateverAdapter {
      LayoutInflater inflater;

      public CustomAdapter(LayoutInflater inflater) {
         this.inflater = inflater;
      }   

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
         return this.inflater.inflate(R.layout.item);
      }   
   }   

}

2 个答案:

答案 0 :(得分:1)

首先,我看不到inflaterMyFragment字段的位置,所以这是一个问题。

其次,我建议不要保留对inflater的引用。它足够便宜,可以获得以下内容:

LayoutInflater inflater = (LayoutInflater) context
    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

(假设您可以在某处访问context。)此外,我不知道哪种适配器具有方法viewAt(int)usual signature是:

public View getView(int position, View convertView, ViewGroup parent) {
    . . .
}

出于性能原因,在每次调用此方法时,绝对不应该为新视图充气。相反,您应该检查convertView参数是否已经是预期类型的​​视图,并且只有在新视图不起作用时才会膨胀。

答案 1 :(得分:0)

你需要使它成为全局变量。试试这个

public class MyFragment extends Fragment {

   LayoutInflater layoutInflater = null;

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
      this.inflater = inflater;
      layoutInflater = inflater;

      MyLayout layout = (MyLayout) inflater.inflate(R.layout.layout);
      SomeAdapterView adapterView  = (SomeAdapterView) layout.findViewById(R.id.adapterView);
      CustomAdapter adapter = new CustomAdapter(inflater);
      adapterView.setAdapter(adapter);

      return layout;
   } 
   ...
}

现在在其他方法的任何地方使用layoutInflater