Search code examples
androidandroid-layoutandroid-arrayadapterandroid-adapter

Finding row layout id in an ArrayAdapter methods


When extending ArrayAdapter with the following code by vogella.com:

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
  private final Context context;
  private final String[] values;

  public MySimpleArrayAdapter(Context context, String[] values) {
    super(context, R.layout.rowlayout, values); // 111
    this.context = context;
    this.values = values;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.rowlayout, parent, false); // 222
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
    textView.setText(values[position]);
    // Change the icon for Windows and iPhone
    String s = values[position];
    if (s.startsWith("Windows7") || s.startsWith("iPhone")
        || s.startsWith("Solaris")) {
      imageView.setImageResource(R.drawable.no);
    } else {
      imageView.setImageResource(R.drawable.ok);
    }

    return rowView;
  }
} 

In the method getView() at the comment "// 222" - is it possible to find the row layout (which was already set in the constructor at the comment "// 111") - or do you have to use the hardcoded value R.layout.rowlayout again (or store it for yourself in the constructor or static final variable)?


Solution

  • You cannot actually access the resource parameter passed to the constructor, since it's private to the ArrayAdapter class.

    You could, however, call super.getView(), which will inflate a new View from the supplied resource id. See the ArrayAdapter code:

    public View getView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(position, convertView, parent, mResource);
    }
    

    However, this presupposes that the layout contains a TextView (with a particular id, that you must supply to the constructor too) or is a TextView itself, so it may not be valid in all cases.