2010/04/02

[Study Note] 코드 또는 XML 리소스를 이용한 Options 메뉴 구현하기

옵션 메뉴를 구성하는 XML 리소스 파일 내용 res/menu/myoptions.xml

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/MnuNew"
android:title="New"
android:icon="@drawable/icon"
/>
<item
android:title="selection"
>
<menu>
<item
android:id="@+id/MnuSelection1"
android:title="Selection1"
android:icon="@drawable/icon"
/>
<item
android:id="@+id/MnuSelection2"
android:title="Selection2"
/>
<item
android:id="@+id/MnuSelection3"
android:title="Selection3"
/>
</menu>
</item>
</menu>




옵션 메뉴 적용하는 코드

package com.neodreamer.MyMenu;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;

public class MyMenu extends Activity
{
static final int MENU_NEW = Menu.FIRST + 0;
static final int MENU_SELECTION1 = Menu.FIRST + 1;
static final int MENU_SELECTION2 = Menu.FIRST + 2;
static final int MENU_SELECTION3 = Menu.FIRST + 3;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public boolean onCreateOptionsMenu( Menu menu )
{
Log.i("Notice", "onCreateOptionsMenu");
/*
// 코드로 직접 구현하는 경우
super.onCreateOptionsMenu(menu);

menu.add( 0, MENU_NEW, 0, "New" )
.setIcon( R.drawable.icon );

SubMenu sub = menu.addSubMenu("Selection");
sub.add( 0, MENU_SELECTION1, 0, "Selection1" )
.setIcon( R.drawable.icon ); // 서브 메뉴는 아이콘 적용 안됨
sub.add( 0, MENU_SELECTION2, 0, "Selection1" );
sub.add( 0, MENU_SELECTION3, 0, "Selection1" );
//*/
//*
// XML menu resource 를 이용하여 구현하는 경우
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.myoptions, menu);
//*/
return true;
}

public boolean onOptionsItemSelected( MenuItem item )
{
Log.i("Notice", "onOptionsMenuSelected");
switch ( item.getItemId() )
{
case MENU_NEW:
Log.i("Code", "MENU_NEW");
break;

case MENU_SELECTION1:
Log.i("Code", "MENU_SELECTION1");
break;

case MENU_SELECTION2:
Log.i("Code", "MENU_SELECTION2");
break;

case MENU_SELECTION3:
Log.i("Code", "MENU_SELECTION3");
break;

case R.id.MnuNew:
Log.i("XML", "MnuNew");
break;

case R.id.MnuSelection1:
Log.i("XML", "MnuSelection1");
break;

case R.id.MnuSelection2:
Log.i("XML", "MnuSelection2");
break;

case R.id.MnuSelection3:
Log.i("XML", "MnuSelection3");
break;
}
return false;
}
}





No comments :

Post a Comment