PopupMenu and PopupMenu
A pop-up menu is a mode menu docked on a View. If there is space below the View object, the pop-up menu will be displayed below the docked object, otherwise it will be displayed above. This is very useful:
Source Code address:Http://download.csdn.net/detail/u013922681/8951537
Reference:
1. Example of PopupMenu for Android
2. Question about Menu position display in Android apps
Source code:
MainActivity. java
package com.example.popMenu;import android.os.Bundle;import android.annotation.SuppressLint;import android.app.Activity;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.PopupMenu;import android.widget.PopupMenu.OnMenuItemClickListener;import android.widget.Toast;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showPopup(View view) { PopupMenu popupMenu = new PopupMenu(MainActivity.this, view); popupMenu.getMenuInflater().inflate(R.menu.main, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.action_settings: Toast.makeText(MainActivity.this, "click", 0).show(); break; default: break; } return false; } }); popupMenu.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.action_settings: Toast.makeText(MainActivity.this, "click", 0).show(); break; default: break; } return super.onOptionsItemSelected(item); }}
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="96dp" android:layout_marginTop="111dp" android:text="@string/hello_world" android:onClick="showPopup"/></RelativeLayout>
Effect
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.