Search code examples
androidandroid-custom-viewlayout-inflater

Android Custom Views vs inflating xml


I have a simple question:

Could you give me some tips about using Custom views vs Layout inflater into executing code? Which one is more preferred to use? Can some one explain me the Pros and Cons of both.

If my question is not clear, the below is an example which explains. Declare it like this:

public class Shortcut extends RelativeLayout{
    private Button btn; 
    private TextView title;


/*some getters & setters here*/


    public Shortcut(Context context){
       LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View v = inflater.inflate(R.layout.shortcut, /*other params*/);
       title = v.findViewById(R.id.title);
       btn = v.findViewById(R.id.btn);
    }

}

And use it like this

public class MainActivit extends Activity{
ListView list = new ListView();

public void onCreate(Bundle...){
    ......
    list.setAdapter(new MyAdapter());
}    
// some code here 

private class MyAdapter extends BaseAdapter{

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Shortcut shortcut = new Shortcut(this);
        shortcut.setBtnText("i'm btn");
        shortcut.setTitle("btn1");
        return shortcut;
    }
}

Or do this way:

public class MainActivit extends Activity{
ListView list = new ListView();

public void onCreate(Bundle...){
    ......
    list.setAdapter(new MyAdapter());
}    
// some code here 

private class MyAdapter extends BaseAdapter{

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
          View view = convertView;
          if (view == null) {
              view = inflater.inflate(R.layout.shortcut, parent, false);
          }          
          TextView title = (TextView) view.findViewById(R.id.title);
          Button btn = (Button) view.findViewById(R.id.btn);
          title.setText("Hey!");
          btn.setText("smth");
           return view;
    }
}

Sorry, if I have some mistakes in my code I printed. it is just here without spellchecking or syntax checking.


Solution

  • I prefer the first way (custom views), because it means all the findViewById() operations are already taken care of, making your code a little neater.

    As per your example:

    Shortcut shortcut = new Shortcut(this);
    shortcut.setBtnText("i'm btn");
    shortcut.setTitle("btn1");
    

    is to me a lot tidier than:

    view = inflater.inflate(R.layout.shortcut, parent, false);
    TextView title = (TextView) view.findViewById(R.id.title);
    Button btn = (Button) view.findViewById(R.id.btn);
    title.setText("Hey!");
    btn.setText("smth");