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,
- 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) {
-
-
- Animation fadeInAnimation = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
- fadeInAnimation.setDuration(10);
- view.startAnimation(fadeInAnimation);
-
-
- popupWindowCategory.dismiss();
-
-
- String selectedItemText = ((TextView) view).getText().toString();
- if (!TextUtils.isEmpty(selectedItemText))
- listner.onSortItemChanged(selectedItemText);
-
-
- }
- });
-
-
- popupWindow.setFocusable(true);
- popupWindow.setWidth(250);
- popupWindow.setHeight(WindowManager.LayoutParams.WRAP_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) {
-
-
- String item = getItem(position);
-
-
- 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;
- }
-
-
- }
Then in in the Activity class on view click do the following,
- 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);
- }
- };