Android应用中使用Popupmenu
最终效果:
页面布局:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:background="#FFFFFF" 6 android:orientation="vertical" > 7 8 <RelativeLayout 9 android:layout_width="fill_parent" 10 android:layout_height="45dp" 11 android:background="#303538" > 12 <Button 13 android:id="@+id/button_showPopup" 14 android:layout_width="wrap_content" 15 android:layout_height="fill_parent" 16 android:layout_alignParentRight="true" 17 android:background="#303538" 18 android:text="┇" 19 android:textColor="#FFFFFF" 20 android:textSize="20sp" > 21 </Button> 22 </RelativeLayout> 23 24 </LinearLayout>
Popupmenu布局(文件在menu目录下):
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 3 4 <item 5 android:id="@+id/about" 6 android:orderInCategory="100" 7 android:showAsAction="never" 8 android:title="关于"> 9 </item> 10 <item 11 android:id="@+id/exit" 12 android:orderInCategory="100" 13 android:showAsAction="never" 14 android:title="退出"> 15 </item> 16 17 </menu>
后台代码:
1 package com.wangzhen.popup; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.MenuItem; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.view.Window; 9 import android.widget.Button; 10 import android.widget.PopupMenu; 11 import android.widget.Toast; 12 13 public class Main extends Activity implements OnClickListener, 14 android.widget.PopupMenu.OnMenuItemClickListener { 15 /** Called when the activity is first created. */ 16 private Button button_showPopup; 17 18 @Override 19 public void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 requestWindowFeature(Window.FEATURE_NO_TITLE); 22 setContentView(R.layout.main); 23 initViews(); 24 } 25 26 // 初始化控件 27 private void initViews() { 28 // TODO Auto-generated method stub 29 button_showPopup = (Button) findViewById(R.id.button_showPopup); 30 button_showPopup.setOnClickListener(this); 31 } 32 33 public void onClick(View arg0) { 34 // TODO Auto-generated method stub 35 switch (arg0.getId()) { 36 case R.id.button_showPopup: 37 PopupMenu pop = new PopupMenu(this, arg0); 38 pop.getMenuInflater().inflate(R.menu.menu, pop.getMenu()); 39 pop.show(); 40 pop.setOnMenuItemClickListener(this); 41 break; 42 } 43 } 44 45 public boolean onMenuItemClick(MenuItem arg0) { 46 // TODO Auto-generated method stub 47 switch (arg0.getItemId()) { 48 case R.id.about: 49 Toast.makeText(this, "关于", 1000).show(); 50 break; 51 case R.id.exit: 52 finish(); 53 break; 54 } 55 return false; 56 } 57 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。