ListView配合popmenu的使用
阿新 • • 發佈:2019-01-10
專案中需要在一個Listview不僅有OnItemClicked還需要item中某一個按鈕具有單獨的點選事件。在安卓官網中 已經有了類似的實現
官網地址https://developer.android.com/samples/ActionBarCompat-ListPopupMenu/index.html
程式碼主要是在ListView的apdater中的getView中
/** * A simple array adapter that creates a list of cheeses. */ class PopupAdapter extends ArrayAdapter<String> { PopupAdapter(ArrayList<String> items) { super而後是點選事件的程式碼(getActivity(), R.layout.list_item, android.R.id.text1, items); } @Override public View getView(int position, View convertView, ViewGroup container) { // Let ArrayAdapter inflate the layout and set the text View view = super.getView(position, convertView, container); // BEGIN_INCLUDE(button_popup)// Retrieve the popup button from the inflated view View popupButton = view.findViewById(R.id.button_popup); // Set the item as the button's tag so it can be retrieved later popupButton.setTag(getItem(position)); // Set the fragment instance as the OnClickListener popupButton.setOnClickListener(PopupListFragment.this); // END_INCLUDE(button_popup) // Finally return the view to be displayed return view; } }
@Override public void onClick(final View view) { // We need to post a Runnable to show the popup to make sure that the PopupMenu is // correctly positioned. The reason being that the view may change position before the // PopupMenu is shown. view.post(new Runnable() { @Override public void run() { showPopupMenu(view); } }); }
// BEGIN_INCLUDE(show_popup) private void showPopupMenu(View view) { final PopupAdapter adapter = (PopupAdapter) getListAdapter(); // Retrieve the clicked item from view's tag final String item = (String) view.getTag(); // Create a PopupMenu, giving it the clicked view for an anchor PopupMenu popup = new PopupMenu(getActivity(), view); // Inflate our menu resource into the PopupMenu's Menu popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu()); // Set a listener so we are notified if a menu item is clicked popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_remove: // Remove the item from the adapter adapter.remove(item); return true; } return false; } }); // Finally show the PopupMenu popup.show(); } // END_INCLUDE(show_popup)這樣就實現了一個listview的一個條目不同點擊事件