Android PopupWindow show as dropdown list example

    In android, PopupWindow is interesting widget and quite hard to approach. To day, I will present an example combined Listview and PopupWindow, hope it's helpful!
    Project description: show a Product ListView and when click at sort icon in header listview, PopupWindow like a dropdownlist appears and show some sorting options (name, price,...).
    Now, launching eclipse and start an android project!
    In order to show PopupWindow as a dropdown list, we must combine it with an sub listview and every listview element is displayed in a PopupWindow row interface.

    This is code for show PopupWindow method:
 /**
  * handle header listview onclick event
  */
 private OnClickListener showPopupWindow() {
  return new OnClickListener() {

   @Override
   public void onClick(View v) {
    PopupWindow popUp = popupWindowsort();
    popUp.showAsDropDown(v, 0, 0); // show popup like dropdown list
   }
  };
 }

 /**
  * show popup window method reuturn PopupWindow
  */
 private PopupWindow popupWindowsort() {

  // initialize a pop up window type
  popupWindow = new PopupWindow(this);

  ArrayList<String> sortList = new ArrayList<String>();
  sortList.add("A to Z");
  sortList.add("Z to A");
  sortList.add("Low to high price");

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
    sortList);
  // the drop down list is a list view
  ListView listViewSort = new ListView(this);

  // set our adapter and pass our pop up window contents
  listViewSort.setAdapter(adapter);

  // set on item selected
  listViewSort.setOnItemClickListener(onItemClickListener());

  // some other visual settings for popup window
  popupWindow.setFocusable(true);
  popupWindow.setWidth(250);
  // popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.white));
  popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

  // set the listview as popup content
  popupWindow.setContentView(listViewSort);

  return popupWindow;
 }

Handling sorting Listview element onclick event (sorting main Listview data):
private OnItemClickListener onItemClickListener() {
  return new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {
    if (position == 0) {
     sortByName(products);
     adapter.notifyDataSetChanged();
    } else if (position == 1) {
     reverseByName(products);
     adapter.notifyDataSetChanged();
    } else {
     sortByPrice(products);
     adapter.notifyDataSetChanged();
     Log.i(TAG, "position2 " + position);
    }
    dismissPopup();
   }
  };
 }

Full MainActivity.java source code (with all sorting methods):
public class MainActivity extends Activity {

 private ListView listView;
 private View headerListView;
 private PopupWindow popupWindow;

 private ArrayList<Product> products;
 private ListViewAdapter adapter;
 private final String TAG = MainActivity.class.getSimpleName();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  listView = (ListView) findViewById(R.id.list);
  setListViewHeader();
  setListViewAdapter();
  createProductList();
 }

 private void setListViewHeader() {
  LayoutInflater inflater = getLayoutInflater();
  ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header_listview, listView, false);
  listView.addHeaderView(header, null, false);

  headerListView = (ImageView) findViewById(R.id.sort);

  // show popup window when click sort icon
  // in listview header
  headerListView.setOnClickListener(showPopupWindow());
 }

 private void createProductList() {
  products.add(new Product(R.drawable.bag, "Travel Bag", "1000"));
  products.add(new Product(R.drawable.calculator, "Casio calculator", "500"));
  products.add(new Product(R.drawable.camera, "Canon Camera", "6000"));
  products.add(new Product(R.drawable.clock, "Alarm Clock", "500"));
  products.add(new Product(R.drawable.book, "Gone with the wind", "300"));
  products.add(new Product(R.drawable.computer, "Acer Laptop", "6000"));
  products.add(new Product(R.drawable.fashion, "T shirt", "200"));
  products.add(new Product(R.drawable.food, "Cake", "50"));
  products.add(new Product(R.drawable.movie, "Saw", "20"));
  products.add(new Product(R.drawable.shoe, "Adidas shoe", "2500"));
  products.add(new Product(R.drawable.travel, "2 day toure", "1500"));
  products.add(new Product(R.drawable.usb, "Kingston Usb", "10"));
  adapter.notifyDataSetChanged();
 }

 private void setListViewAdapter() {
  products = new ArrayList<Product>();
  adapter = new ListViewAdapter(this, R.layout.item_listview, products);
  listView.setAdapter(adapter);
 }

 /**
  * handle header listview onclick event
  */
 private OnClickListener showPopupWindow() {
  return new OnClickListener() {

   @Override
   public void onClick(View v) {
    PopupWindow popUp = popupWindowsort();
    popUp.showAsDropDown(v, 0, 0); // show popup like dropdown list
   }
  };
 }

 /**
  * show popup window method reuturn PopupWindow
  */
 private PopupWindow popupWindowsort() {

  // initialize a pop up window type
  popupWindow = new PopupWindow(this);

  ArrayList<String> sortList = new ArrayList<String>();
  sortList.add("A to Z");
  sortList.add("Z to A");
  sortList.add("Low to high price");

  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
    sortList);
  // the drop down list is a list view
  ListView listViewSort = new ListView(this);

  // set our adapter and pass our pop up window contents
  listViewSort.setAdapter(adapter);

  // set on item selected
  listViewSort.setOnItemClickListener(onItemClickListener());

  // some other visual settings for popup window
  popupWindow.setFocusable(true);
  popupWindow.setWidth(250);
  // popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.white));
  popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);

  // set the list view as pop up window content
  popupWindow.setContentView(listViewSort);

  return popupWindow;
 }

 private OnItemClickListener onItemClickListener() {
  return new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {
    if (position == 0) {
     sortByName(products);
     adapter.notifyDataSetChanged();
    } else if (position == 1) {
     reverseByName(products);
     adapter.notifyDataSetChanged();
    } else {
     sortByPrice(products);
     adapter.notifyDataSetChanged();
     Log.i(TAG, "position2 " + position);
    }
    dismissPopup();
   }

  };
 }

 private void dismissPopup() {
  if (popupWindow != null) {
   popupWindow.dismiss();
  }
 }

 /**
  * sort products by name A - Z
  */
 private void sortByName(ArrayList<Product> productList) {
  Collections.sort(productList, new Comparator<Product>() {
   public int compare(Product v1, Product v2) {
    return v1.getName().compareTo(v2.getName());
   }
  });
 }

 /**
  * sort produts by name Z - A
  */
 private void reverseByName(ArrayList<Product> productList) {
  Collections.sort(productList, Collections.reverseOrder(new Comparator<Product>() {

   @Override
   public int compare(Product lhs, Product rhs) {
    return lhs.getName().compareTo(rhs.getName());
   }

  }));
 }

 /**
  * sort products by price (low to high)
  * 
  * @param productList
  */
 private void sortByPrice(ArrayList<Product> productList) {
  Collections.sort(productList, new PriceComparator());
 }

 private static class PriceComparator implements Comparator<Product> {
  public int compare(Product c1, Product c2) {
   return Integer.valueOf(c1.getPrice()).compareTo(Integer.valueOf(c2.getPrice()));
  }
 }
}

This activity layout (activity_main.xml) simple like this: Therefor, we must create a Custom Listview Adapter base on ArrayAdapter.
Source code for ListviewAdapter.java:
public class ListViewAdapter extends ArrayAdapter<Product> {

 private Activity activity;
 private ArrayList<Product> products;
 private final String TAG = ListViewAdapter.class.getSimpleName();

 public ListViewAdapter(Activity activity, int resource, ArrayList<Product> products) {
  super(activity, resource, products);
  this.activity = activity;
  this.products = products;
  Log.i(TAG, "init adapter");
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  ViewHolder holder = null;

  // inflate layout from xml
  LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

  // If holder not exist then locate all view from UI file.
  if (convertView == null) {
   // inflate UI from XML file
   convertView = inflater.inflate(R.layout.item_listview, parent, false);
   // get all UI view
   holder = new ViewHolder(convertView);
   // set tag for holder
   convertView.setTag(holder);
  } else {
   // if holder created, get tag from view
   holder = (ViewHolder) convertView.getTag();
  }

  Product product = products.get(position);

  // set product data to views
  holder.image.setImageResource(product.getImageId());
  holder.name.setText(product.getName());
  holder.price.setText(product.getPrice());

  // the view must be returned to our activity
  return convertView;
 }

 private class ViewHolder {
  private ImageView image;
  private TextView name;
  private TextView price;

  public ViewHolder(View v) {
   image = (ImageView) v.findViewById(R.id.image);
   name = (TextView) v.findViewById(R.id.name);
   price = (TextView) v.findViewById(R.id.price);
  }
 }

}

Finally, these are some necessary layout:
- Listview header layout (header_listview.xml): - Layour for every main Listview item(item_listview.xml): Finally, running program and we will see this result (click each image for full screen):

pic name pic name pic name

(sorry for ads in download link)

Share


Previous post
« Prev Post
Next post
Next Post »