android
안드로이드 팝업메뉴( PopupMenu ) 사용 예제 / 옵션메뉴처럼 사용
관절분리
2018. 11. 12. 11:33
반응형
안드로이드 팝업메뉴( PopupMenu ) 사용 예제
1. 팝업메뉴 생성 PopupMenu( 현재 화면의 제어권자, 팝읍을 뛰울 기준좌표 위젯);
2. menu 리소스에서 메뉴 불러오기 :
getMenuInflater().inflate(R.menu.menu_main, p.getMenu())
3. PopupMenu.setOnMenuItemClickListener() 에서 onMenuItemClick() 오버라이딩
4. PopupMenu.show() 로 화면에 띄우기
[메인 액티비티 소스]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b = (Button)findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 버튼 클릭시 팝업 메뉴가 나오게 하기 // PopupMenu 는 API 11 레벨부터 제공한다 PopupMenu p = new PopupMenu( getApplicationContext(), // 현재 화면의 제어권자 v); // anchor : 팝업을 띄울 기준될 위젯 getMenuInflater().inflate(R.menu.menu_main, p.getMenu()); // 이벤트 처리 p.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Toast.makeText(getApplicationContext(), "팝업메뉴 이벤트 처리 - " + item.getTitle(), Toast.LENGTH_SHORT).show(); return false; } }); p.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.menu_main, menu); return true; } public void dd(View v) { Toast.makeText(getApplicationContext(), "dd", Toast.LENGTH_SHORT).show(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == 1) { return true; } return super.onOptionsItemSelected(item); } } | cs |
[메뉴 xml]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/w" android:title="submenu 1" > <menu> <item android:title="apple"/> <item android:title="babana"/> <item android:title="remon"/> </menu> </item> <item android:id="@+id/d" android:title="submenu 2" > <menu > <item android:title="사과"/> <item android:title="배"/> <item android:title="수박"/> </menu> </item> <item android:id="@+id/c" android:title="submenu 3" /> </menu> | cs |
[실행화면]
아래에서 버튼을 눌러도 PopupMenu 가 나오고 우상단의 옵션 버튼을 눌러도 나옵니다.
출처: http://bitsoul.tistory.com/20 [Happy Programmer~]
반응형