知識(shí)點(diǎn)
今天繼續(xù)昨天沒(méi)有講完的Menu的學(xué)習(xí),主要是Popup Menu的學(xué)習(xí)。
Popup Menu(彈出式菜單)
彈出式菜單是一種固定在View上的菜單模型。主要用于以下三種情況:
為特定的內(nèi)容提供溢出風(fēng)格(overflow-style)的菜單進(jìn)行操作。
提供其他部分的命令句(command sentence)如Add按鈕可以用彈出菜單提供不同的Add的操作。
提供類(lèi)似于Spinner的下拉式菜單但不保持持久的選擇。
那怎樣顯示彈出式菜單呢?
如果你在XML文件中定義了菜單,那么以下三步就可顯示:
1.用PopupMenu的構(gòu)造器實(shí)例化彈出式菜單,需要當(dāng)前應(yīng)用的Context和菜單需要固定到的View。
2.使用MenuInflater填充你的菜單資源到Menu對(duì)象中,這個(gè)Menu對(duì)象是由PopupMenu.getMenu返回的(在API 14和以上 可以用PopupMenu.inflater替代)
3.調(diào)用PopupMenu.show()
下面通過(guò)一個(gè)例子來(lái)理解PopupMenu的使用:
public void showPopup(View v){ PopupMenu popup = new PopupMenu(this,v); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.popup, popup.getMenu()); popup.setOnMenuItemClickListener(this); popup.show(); } @Override public boolean onMenuItemClick(MenuItem arg0) { switch (arg0.getItemId()) { case R.id.item1: Toast.makeText(this, "you have clicked the item 1", Toast.LENGTH_LONG).show(); break; case R.id.item2: Toast.makeText(this, "you have clicked the item 2", Toast.LENGTH_LONG).show(); break; case R.id.item3: Toast.makeText(this, "you have clicked the item 3", Toast.LENGTH_LONG).show(); break; default: break; } return false; }
<LinearLayout 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:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/clickMe" android:onClick="showPopup" android:clickable="true"/> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" android:clickable="true" android:onClick="showPopup" /> </LinearLayout>
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注