How can I add a hint to the Spinner widget? [duplicate]

和自甴很熟 提交于 2019-12-29 06:40:36

问题


I have a Spinner in spinnerMode="dropdown" mode. Instead of the preselected first item, I want to show the user a hint, so that there is no default selection (like »Please select an item«)

This is the UI I got:

and this is the UI I want to achive:

I figured that the EditText widget has an android:hint attribute, but not the Spinner widget and setting it doesn't bring me the the UI I want. This is an Android 4.x-only app, so I don't have to hassle with any pre-4.0 compatibility stuff.


回答1:


I haven't found an easy and clean solution yet, only this workaround using custom adapters and a custom item class:

First, we need a class for the spinner item content:

class SpinnerItem {
        private final String text;
        private final boolean isHint;

        public SpinnerItem(String strItem, boolean flag) {
            this.isHint = flag;
            this.text = strItem;
        }

        public String getItemString() {
            return text;
        }

        public boolean isHint() {
            return isHint;
        }
    }

Then our adapter class:

class MySpinnerAdapter extends ArrayAdapter<SpinnerItem> {
        public MySpinnerAdapter(Context context, int resource, List<SpinnerItem> objects) {
            super(context, resource, objects);
        }

        @Override
        public int getCount() {
            return super.getCount() - 1; // This makes the trick: do not show last item
        }

        @Override
        public SpinnerItem getItem(int position) {
            return super.getItem(position);
        }

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

    }

Finally we use the workaround like this:

ArrayList<SpinnerItem> items = new ArrayList<SpinnerItem>();
        items.add(new SpinnerItem("Item 1", false));
        items.add(new SpinnerItem("Item 2", false));
        items.add(new SpinnerItem("HINT", true)); // Last item 

        MySpinnerAdapter adapter = new MySpinnerAdapter(this, android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(items.size() - 1);

Then you can use the flag from the SpinnerItem class to set text color for that item or whatever.



来源:https://stackoverflow.com/questions/13877681/how-can-i-add-a-hint-to-the-spinner-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!