Here I am going to tell you how can we show a custom popup listview on clicking on a button or a view in Android, First you need the following class to show popup,
Then in in the Activity class on view click do the following,public class CategoryPopUp { private PopupWindow popupWindowCategory; ArrayList<String> categories = null; private Context context = null; private SortCategoryChangeListner listner = null; public CategoryPopUp(ArrayList<String> categories, Context context, SortCategoryChangeListner listner) { this.context = context; this.categories = categories; this.listner = listner; } public void showWindow(View view) { popupWindowCategory = getPopupWindowCategory(categories); popupWindowCategory.showAsDropDown(view, -5, 0); } public PopupWindow getPopupWindowCategory(ArrayList<String> categories) { PopupWindow popupWindow = new PopupWindow(context); ListView listViewDogs = new ListView(context); listViewDogs.setAdapter(categoryAdapter(categories)); listViewDogs.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // add some animation when a list item was clicked Animation fadeInAnimation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); fadeInAnimation.setDuration(10); view.startAnimation(fadeInAnimation); // dismiss the pop up popupWindowCategory.dismiss(); // get the text and set it as the button text String selectedItemText = ((TextView) view).getText().toString(); if (!TextUtils.isEmpty(selectedItemText)) listner.onSortItemChanged(selectedItemText); } }); // some other visual settings popupWindow.setFocusable(true); popupWindow.setWidth(250); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); // set the list view as pop up window content popupWindow.setContentView(listViewDogs); return popupWindow; } private ArrayAdapter<String> categoryAdapter(ArrayList<String> categories) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, categories) { @Override public View getView(int position, View convertView, ViewGroup parent) { // setting the ID and text for every items in the list String item = getItem(position); // visual settings for the list item TextView listItem = new TextView(context); listItem.setText(item); listItem.setTag(item); listItem.setTextSize(12); listItem.setPadding(10, 10, 10, 10); listItem.setTextColor(Color.WHITE); return listItem; } }; return adapter; } }
View.OnClickListener sortListner = new View.OnClickListener() { @Override public void onClick(View view) { ArrayList<String> categories = new ArrayList<String>(); categories.add("all"); categories.add("category 1"); categories.add("category 2"); categories.add("category 3"); categories.add("category 4"); categories.add("category 5"); categories.add("category 6"); new CategoryPopUp(categories, getActivity(), MyReferralFragment.this).showWindow(view); } };
