Android data binding spinner adapter

1.4k views Asked by At

I have to write a @BindingAdapter which accepts Spinner and EnumSet<T> :

@BindingAdapter(value = {"android:entries"})
public static <T extends Enum<T> & ITextable> void bindSpinnerData(Spinner spinner, EnumSet<T> entries) {
    spinner.setAdapter(new ArrayAdapter<T>(spinner.getContext(), R.layout.support_simple_spinner_dropdown_item, new ArrayList<>(entries)) {
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View v = super.getView(position, convertView, parent);
            TextView textView = (TextView) v.findViewById(android.R.id.text1);
            ITextable item = getItem(position);
            textView.setText(item.getText());
            return v;
        }

        @Override
        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View v = super.getDropDownView(position, convertView, parent);
            TextView textView = (TextView) v.findViewById(android.R.id.text1);
            ITextable item = getItem(position);
            textView.setText(item.getText());
            return v;
        }
    });
}

I have a problem because if the text of a Spinner item is too long to fit into a single line, the text is not wrapped but cut off like this:

enter image description here

Can anyone tell my where and what I should change to wrap the text?

1

There are 1 answers

2
Emanuel On BEST ANSWER

It's actually not a databinding-issue. It's because TextView arent wrapped by default and also doesnt have elipses if you dont set them.

You may want to try either to create your own Layout which gets inflated, or you may use

textView.setSingleLine(false)
textView.setMaxLines(2)

If this doesnt work you need to overwrite getDropDownView

@Override
public View getDropDownView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = new TextView(_context);
    }

    TextView item = (TextView) convertView;
    item.setText(yourItems.getItem(position));
    final TextView finalItem = item;
    item.post(new Runnable() {
        @Override
        public void run() {
            finalItem.setSingleLine(false);
        }
    });
    return item;
}

Easiest solution is just switch your Spinner using dialog design by putting this into your xml.

 <Spinner android:spinnerMode="dialog" />