Your experience on this site will be improved by allowing cookies
popup manu android
To display the menu below the anchor text or above the anchor text (in case the space is not available above), the Android Popup Menu is used. On clicking outside the popup menu, the menu disappears. The java.lang.Object class has the android.widget.PopupMenu as a direct subclass.
In the below example, we will demonstrate the way to create a popup menu in android.
activity_main.xml:
In the activity_main.xml file, we will add only one button.
popup_menu.xml:
The popup_menu that contains the items is created inside the res/menu directory.
Activity class:(File: MainActivity.java)
In the MainActivity.java file, we will write the code to display the popup menu on button click.
package com.example.radioapp; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.PopupMenu; import android.widget.Toast; public class MainActivity extends AppCompatActivity { Button popupButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); popupButton = findViewById(R.id.popup); popupButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupMenuExample(); } }); } private void popupMenuExample() { PopupMenu p = new PopupMenu(MainActivity.this, popupButton); p.getMenuInflater().inflate(R.menu.popup_menu, p .getMenu()); p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Toast.makeText(MainActivity.this,item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); p.show(); } |
0 comments