Android- How to add Hint on Spinner?

DWQA QuestionsCategory: android questionAndroid- How to add Hint on Spinner?
kamal bunkar Staff asked 8 months ago

I want to show hint on drop-down(Spinner) list but I am not getting how to add hint on spinner. I added hint text on list but It doesn’t look like hint.  I want something like below pic. Is there any android library available to show hint on spinner?

android-how to add hint on spinner

on click on stock availability, it must look like this

android how to app hint on spinner

1 Answers
kamal bunkar Staff answered 8 months ago

It is very easy to create hint on spinner. There is a github library for spinner hint. All you have to do is add dependency on gradle file.

// spinner with hint
compile 'me.srodrigo:androidhintspinner:1.0.0'

Activity.xml file- don't need to add anything just put a spinner
<Spinner
android:id="@+id/stock_avail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/margin_large_30"
android:layout_marginRight="@dimen/margin_large_30"
android:layout_marginTop="@dimen/margin_large" />
MainActivity.java file- add custom hint adapter for spinner

private ArrayList<String> stockAvaillist = new ArrayList<String>();
private HintAdapter<String> stock_adapter;

  stockAvaillist.add(AppUtils.getStrFromRes(R.string.instock));
stockAvaillist.add(AppUtils.getStrFromRes(R.string.outoffstock));
// stock_avail.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stockAvaillist));
stock_adapter = new HintAdapter<String>(this, R.string.stock_avail, stockAvaillist);
HintSpinner<String> stockSpinner = new HintSpinner<>(
stock_avail,
// Default layout - You don't need to pass in any layout id, just your hint text and
// your list data
stock_adapter,
new HintSpinner.Callback<String>() {
@Override
public void onItemSelected(int position, String itemAtPosition) {
// Here you handle the on item selected event (this skips the hint selected event)
// Log.e(TAG, "stock select "+String.valueOf(position)+" "+ stockAvaillist.get(position));
if (stockAvaillist.get(position).equalsIgnoreCase(AppUtils.getStrFromRes(R.string.instock))){
stock_avail_flag = "1";
}else if (stockAvaillist.get(position).equalsIgnoreCase(AppUtils.getStrFromRes(R.string.outoffstock))){
stock_avail_flag ="0" ;
}
}
});
stockSpinner.init();