Monday 10 February 2014

Android - how to make a custom view which looks like a Spinner

I'll show you in this post how to make a custom view which looks like a Spinner and to which you can assign your own text and click listener. There's just two steps.

Step 1 - define an xml layout for your custom view as follows:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/view_root"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  style="?android:attr/spinnerStyle" >

  <include
    layout="@android:layout/simple_spinner_item"
    android:id="@+id/view_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</FrameLayout>

We'll assume you've saved the above layout in res/layout/spinner_lookalike.xml.

Step 2 - create your custom view class as follows:

/**
 * This class is essentially a {@link FrameLayout}
 * which looks like a {@link Spinner}.
 */
public class SpinnerLookalikeView extends FrameLayout {

  private ViewGroup rootView;
  private TextView textView;

  /**
   * Constructor to use when creating View from code.
   * */
  public SpinnerLookalikeView(Context context) {
    super(context);
    initialise();
  }

  /**
   * Constructor that is used when inflating View from XML.
   * */
  public SpinnerLookalikeView(Context context, AttributeSet attrs) {
    super(context, attrs);
      initialise();
  }

  /**
   * Constructor that is used when inflating View from XML
   * and applying a class-specific base style.
   * */
  public SpinnerLookalikeView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    initialise();
  }

  @Override
  public void setOnClickListener(OnClickListener listener) {
    rootView.setOnClickListener(listener);
  }

  /**
   * Sets the text shown in this view.
   * 
   * @param text
   */
  public void setText(String text) {
    textView.setText(text);
  }

  /**
   * Initialisation method to be called by the constructors of this class only.
   */
  private void initialise() {
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.spinner_lookalike, this);

    rootView = (ViewGroup) findViewById(R.id.view_root);
    textView = (TextView) findViewById(R.id.view_text);
  }

}

That's it! Now you can add this custom view to your activities and assign text and a click listener to it.