Usage example of PopupMenu component in Android
Recently, I studied the use of PopupMenu component in Android and found it very practical, so I left a note for future query
It is estimated that many people have encountered this scenario:
The popupwindow required to pop up is a list. When we use it, we set a listview or recyclerview in it. Now we don't need to do such tedious work.
The PopupMenu component provided under the official android.support.v7.widget package has been adopted by more and more projects. Let's take a look at the effects of several apps:
This is a very lightweight context menu component, simple and easy to use.
1. Create a resource file
Create a new menu folder in the res directory. This folder is mainly used to store menu resource files. Let's create a new sample_ Menu.xml file:
Write down a few menu options.
2. Show in code
Sometimes we need to show or hide the specified item according to different conditions. For example, when clicking the second button, we need to hide the option of "delete song", and only need to add a few lines of code:
Sometimes we need to show or hide the specified item according to different conditions. For example, when clicking the second button, we need to hide the option of "delete song", and only need to add a few lines of code:
Let's see the effect:
PopupMenu is displayed below the specified control by default, but the display position will be automatically adjusted when insufficient space is detected. And with its own animation effect, isn't it very convenient?
3. Display icon in PopupMenu
In the past, menus with icons were usually implemented by customizing popupwindow, which is troublesome. In fact, PopupMenu can easily realize this function, but reflection is required. I don't understand reflection deeply, so the following code is pasted from the Internet. Careful students may find that in the XML resource file, I write the attribute of icon in each item tag. Yes, what you want to display is the picture set here. Of course, if you don't need to display icons, there's no need to write icons.
Final effect:
I've thought so much about the use of PopupMenu for the time being. I'll add more skills in the future.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.