0

When my spinner positioned at the actionbar is clicked, it's supposed to present a dropdown with an array of items. Every viewholder for an item has a name and a photo.

However, I want the spinner's title to be another layout (text-only).

In short: How can I set a layout for the title spinner that differs from the dropdown layout?

Main.java

SpinnerAdapter spinnerAdapter = new SpinnerAdapter(this, dummyLists);
    mMyListsSpinner.setAdapter(spinnerAdapter);

SpinnerAdapter.java

private class SpinnerAdapter extends BaseAdapter {
    private String[] mListNames;
    SpinnerAdapter(Context context, String[] listNames) {
        this.mListNames = listNames;
    }

    @Override
    public int getCount() {
        if(this.mListNames == null) {
            return 0;
        }
        return this.mListNames.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Context context = parent.getContext();

        int spinnerItemViewLayout = R.layout.layout_spinner_dropdown_item;

        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(spinnerItemViewLayout, parent, false);

        TextView nameTextView = (TextView) view.findViewById(R.id.tv_spinner_list_name);
        nameTextView.setText(this.mListNames[position]);

        return view;
    }
}

layout_spinner_dropdown_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout_spinner_dropdown_item"
android:layout_width="222dp"
android:layout_height="@dimen/toolbar_actionbar_height"
android:orientation="horizontal">

<TextView
    android:id="@+id/tv_spinner_list_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="LIST"
    android:textSize="@dimen/text_size_subheading"
    android:textColor="@color/color_green_dark"/>

<ImageView
    android:layout_width="42dp"
    android:layout_height="42dp"
    android:layout_centerVertical="true"
    android:layout_alignParentRight="true"
    android:src="@color/color_green_dark"/>
</RelativeLayout>
elanonrigby
  • 479
  • 1
  • 6
  • 14

1 Answers1

0

This may be helpful: Android Spinner with different layouts for “drop down state” and “closed state”?

Basic points:

  1. Rewrite getView() and getDropDownView() in your Adapter class [SpinnerAdapter]
  2. In getView(), you should inflate normal layout for title bar, in your case it's a TextView only. In getDropDownView(), you should inflate your layout_spinner_dropdown_item.xml.
Keale
  • 3,924
  • 3
  • 29
  • 46
lution
  • 81
  • 12