C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Android Popup Menu ExampleAndroid Popup Menu displays the menu below the anchor text if space is available otherwise above the anchor text. It disappears if you click outside the popup menu. The android.widget.PopupMenu is the direct subclass of java.lang.Object class. Android Popup Menu ExampleLet's see how to create popup menu in android. activity_main.xmlIt contains only one button. File: activity_main.xml
popup_menu.xmlIt contains three items as show below. It is created inside the res/menu directory. File: poupup_menu.xml
Activity classIt displays the popup menu on button click. File: MainActivity.java
package example.TheDeveloperBlog.com.popupmenu; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; 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 button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Creating the instance of PopupMenu PopupMenu popup = new PopupMenu(MainActivity.this, button); //Inflating the Popup using xml file popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { Toast.makeText(MainActivity.this,"You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show(); return true; } }); popup.show();//showing popup menu } });//closing the setOnClickListener method } } Output:
Next TopicAndroid Service Tutorial
|