Android > Popup Menu - ¸¸µé±â
µî·ÏÀÏ : 2017-07-05 18:42
Á¶È¸¼ö : 53,273
¹öÆ°À» Ŭ¸¯ÇßÀ»¶§ Æ˾÷¸Þ´º¸¦ Ç¥½ÃÇÏ°íÀÚ ÇÒ¶§´Â PopupMenu À§Á¬À» »ç¿ëÇÏ¸é µË´Ï´Ù.
¿À´ÃÀº Æ˾÷¸Þ´º¸¦ ¸¸µå´Â ¹æ¹ýÀ» ¾Ë¾Æº¸µµ·Ï ÇÏ°Ú½À´Ï´Ù.
activity_main.xml ÆÄÀÏ¿¡´Â ÇϳªÀÇ ¹öÆ°ÀÌ ÀÖ½À´Ï´Ù. "btn_popupmenu" ¹öÆ° ÀÔ´Ï´Ù.
À̹öÆ°À» Ŭ¸¯ÇßÀ»¶§ Æ˾÷âÀ» ¶ç¿ì´Â ¹æ¹ýÀÔ´Ï´Ù.
¸ÕÀú Æ˾÷¸Þ´º¿¡ »ç¿ëÇÒ ¸Þ´º¾ÆÀÌÅÛ 3°³¸¦ ¸¸µì´Ï´Ù.
res/menu/popup_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/save"
android:title="SAVE"
android:icon="@android:drawable/ic_menu_save" />
<item
android:id="@+id/search"
android:title="SEARCH"
android:icon="@android:drawable/ic_menu_search" />
<item
android:id="@+id/setting"
android:title="SETTING"
android:icon="@android:drawable/ic_menu_edit" />
</menu>
MainActivity.java ÆÄÀÏ¿¡ ±âº» ÇÁ·Î±×·¡¹ÖÀ» ÇÕ´Ï´Ù.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_popupmenu).setOnClickListener(this); //·Î±×ÀιöÆ°
}
@Override
public void onClick(View v){
switch( v.getId() ){
case R.id.btn_popupmenu:
//PopupMenu°´Ã¼ »ý¼º.
//»ý¼ºÀÚÇÔ¼öÀÇ Ã¹¹øÀç ÆĶó¹ÌÅÍ : Context
//»ý¼ºÀÚÇÔ¼öÀÇ µÎ¹ø° ÆĶó¹ÌÅÍ : Popup Menu¸¦ ºÙÀÏ anchor ºä
PopupMenu popup= new PopupMenu(this, v);//v´Â Ŭ¸¯µÈ ºä¸¦ ÀǹÌ
//Popup Menu¿¡ µé¾î°¥ MenuItem Ãß°¡.
//ÀÌÀü Æ÷½ºÆ®ÀÇ ÄÁÅؽºÆ® ¸Þ´º(Context menu)ó·³ xml ¸Þ´º ¸®¼Ò½º »ç¿ë
//ù¹øÀç ÆĶó¹ÌÅÍ : resÆú´õ>>menuÆú´õ>>mainmenu.xmlÆÄÀÏ ¸®¼Ò½º
//µÎ¹øÀç ÆĶó¹ÌÅÍ : Menu °´Ã¼->Popup Menu °´Ã¼·Î ºÎÅÍ Menu °´Ã¼ ¾ò¾î¿À±â
getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//Popup MenuÀÇ MenuItemÀ» Ŭ¸¯ÇÏ´Â °ÍÀ» °¨ÁöÇÏ´Â listener ¼³Á¤
popup.setOnMenuItemClickListener(listener);
popup.show();//Popup Menu º¸À̱â
break;
}
}
//Popup MenuÀÇ MenuItemÀ» Ŭ¸¯ÇÏ´Â °ÍÀ» °¨ÁöÇÏ´Â listener °´Ã¼ »ý¼º
//import android.widget.PopupMenu.OnMenuItemClickListener °¡ µÇ¾îÀÖ¾î¾ß ÇÕ´Ï´Ù.
//OnMenuItemClickListener Ŭ·¡½º´Â ´Ù¸¥ ÆÐÅ°Áö¿¡µµ ¸¹±â ¶§¹®¿¡ PopupMenu¿¡ ¹ÝÀÀÇÏ´Â ÆÐÅ°Áö¸¦ ÀÓÆ÷Æ®ÇÏ¼Å¾ß ÇÕ´Ï´Ù.
OnMenuItemClickListener listener= new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
switch( item.getItemId() ){//´·¯Áø MenuItemÀÇ Item Id¸¦ ¾ò¾î¿Í ½Äº°
case R.id.save:
Toast.makeText(MainActivity.this, "SAVE", Toast.LENGTH_SHORT).show();
break;
case R.id.search:
Toast.makeText(MainActivity.this, "SEARCH", Toast.LENGTH_SHORT).show();
break;
case R.id.setting:
Toast.makeText(MainActivity.this, "SETTING", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
};
}
Æ˾÷¸Þ´º¸¦ ¶ç¿ì´Â ¼Ò½º°¡ ¿Ï¼ºµÇ¾ú½À´Ï´Ù. ºÐ¼®ÇØ º¸¸é ¾î·ÆÁö ¾Ê°Ô ±¸ÇöÇÒ ¼ö ÀÖ½À´Ï´Ù.