With help of @Chetan's Answer I built this widget which may help anyone
Please provide list of options using
setOptions
method
public class DropDown extends AppCompatTextView implements View.OnClickListener {
private ArrayList<String> options = new ArrayList<>();
public DropDown(Context context) {
super(context);
initView();
}
public DropDown(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public DropDown(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView() {
this.setOnClickListener(this);
}
private PopupWindow popupWindowsort(Context context) {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(context);
popupWindow.setWidth(this.getWidth());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line,
options);
// the drop down list is a list view
ListView listViewSort = new ListView(context);
// set our adapter and pass our pop up window contents
listViewSort.setAdapter(adapter);
// set on item selected
listViewSort.setOnItemClickListener((parent, view, position, id) -> {
this.setText(options.get(position));
popupWindow.dismiss();
});
// some other visual settings for popup window
popupWindow.setFocusable(true);
// popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.white));
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
// set the listview as popup content
popupWindow.setContentView(listViewSort);
return popupWindow;
}
@Override
public void onClick(View v) {
if (v == this) {
PopupWindow window = popupWindowsort(v.getContext());
window.showAsDropDown(v, 0, 0);
}
}
public void setOptions(ArrayList<String> options) {
this.options = options;
}
}
in your layout file
<com.yourdomian.app.DropDown
style="@style/formDropDown"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/ship_to_address" />
in your style file
<style name="formDropDown">
<item name="android:paddingRight">20dp</item>
<item name="android:paddingLeft">24dp</item>
<item name="android:paddingTop">20dp</item>
<item name="android:paddingBottom">20dp</item>
<item name="android:textSize">13sp</item>
<item name="android:background">@drawable/edit_text_background_dark_round</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:elevation">5dp</item>
<item name="android:drawableRight">@drawable/ic_down_arrow</item>
<item name="android:gravity">center_vertical</item>
</style>
In your Java File
ArrayList<String> options = new ArrayList<>();
options.add("Option 1");
options.add("Option 2");
options.add("Option 3");
options.add("Option 4");
((DropDown)findViewById(R.id.dropdown)).setOptions(options);
Output will be