Home > Mobile >  How to apply custom drop down style on custom spinner adapter?
How to apply custom drop down style on custom spinner adapter?

Time:01-02

I created custom spinner adapter class (source code bellow), because I needed to apply custom design for spinner (i.e. custom_spinner_item). That part is ok and everything shows as I intended.

CustomSpinnerAdapter.java

public class CustomSpinnerAdapter extends BaseAdapter {

    private Context context;
    private String[] cities;

    public CustomSpinnerAdapter(Context context, String[] cities) {
        this.context = context;
        this.cities = cities;
    }

    @Override
    public int getCount() {
        return cities != null ? cities.length : 0;
    }

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rootView = LayoutInflater.from(context).inflate(R.layout.custom_spinner_item, viewGroup, false);

        TextView txtName = rootView.findViewById(R.id.customSpinnerItemTextView);
        txtName.setText(cities[i]);

        return rootView;
    }
}

custom_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@ id/customSpinnerItemTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="City"
        android:layout_centerVertical="true"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="22dp"
        android:textAppearance="@style/toolbar_text_white"/>

</LinearLayout>

Problems start to appear during styling of drop down view of spinner. Since my custom adapter class is NOT ArrayAdapter<CharSequence> derivative, I cannot apply setDropDownViewResource method on its objects, so I cannot easily apply XML description of drop down view like I did with custom_spinner_item. I need somehow to apply custom drop down view XML description on my custom adapter. Does someone have any idea how to achieve described? Thanks!

CodePudding user response:

You can override getDropDownView() in BaseAdapter to define a custom drop down item layout.

getDropDownView() can be built like getView(); preferably with a ViewHolder pattern (you should do that in getView() as well) to help in view recycling.

  • Related