Question

I realize that in situations like this, the idiom is to pass a Context to the CustomAdapter constructor, and with it create a LayoutInflater. But I'm wondering nonetheless whether there is anything wrong with the code below.

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

}
Was it helpful?

Solution

First, I don't see where inflater is a field of MyFragment, so that's a problem.

Second, I would recommend against keeping a reference to an inflater. It's cheap enough to obtain an inflater with:

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

(assuming you have access to a context somewhere.) Also, I don't know what kind of adapter has a method viewAt(int). The usual signature is:

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

For performance reasons, you should definitely not inflate a new view on every call to this method. Instead you should check whether the convertView argument is already a view of the expected type and only inflate a new view if it won't work.

OTHER TIPS

You need to make it Global variable. Try this

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

Now use layoutInflater anywhere in other methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top