[Android] CheckMenu Android 2011. 12. 16. 11:19
체크 메뉴는 체크 박스 통한 선택이나 라디오 버튼을 통한 선택적인 메뉴를 나타 낼 수 있다.

라디오 박스의 경우 group을 통하여 서로 꼭 묵어주는 것을 잊으면 안된다.

또한 이 메뉴는 컨텍스트 메뉴와 서브 메뉴에서만 사용이 가능하다.

다음은 그 예시 코드 이다.

main.xml

<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"       
        android:text="Button"
        android:textSize="20px"
        />

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/submenu"
       android:title="SubMenu">
       <menu>
           <group
               android:id="@+id/checkble_group"
              android:checkableBehavior="all">
              <item
               android:id="@+id/bigfont"
               android:title="BigFont"
               />
           </group>
           <group
               android:id="@+id/exclusive_checkable_group"
               android:checkableBehavior="single">
              <item android:id="@+id/red"
                    android:title="RED"
                    android:checked="true"/>
              <item android:id="@+id/green"
                    android:title="GREEN"
                    android:checked="true"/>
              <item android:id="@+id/blue"
                    android:title="BLUE"
                    android:checked="true"/>
          </group>   
       </menu>   
 </item>
</menu>

java

Button btn;
 @Override   
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button)findViewById(R.id.btn);
    }
 
 @Override 
 public boolean onCreateOptionsMenu(Menu menu){
  super.onCreateOptionsMenu(menu);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.menu,menu);
  return true;
 }
 
 @Override
 public boolean onPrepareOptionsMenu(Menu menu){
  if(btn.getTextSize()==40){
   menu.findItem(R.id.bigfont).setChecked(true);
  }
  else{
   menu.findItem(R.id.bigfont).setChecked(false);
  }
  
  int color = btn.getTextColors().getDefaultColor();
  
  if(color==Color.RED){
   menu.findItem(R.id.red).setChecked(true);
  }
  else if(color==Color.GREEN){
   menu.findItem(R.id.green).setChecked(true); 
  }
  else if(color==Color.BLUE){
   menu.findItem(R.id.blue).setChecked(true);
  }
  return true;
 }
 @Override 
 public boolean onOptionsItemSelected(MenuItem item){
  switch(item.getItemId()){
  case R.id.bigfont:
   if(item.isCheckable()){
    btn.setTextSize(20);
   }
   else{
    btn.setTextSize(40);
   }
   return true;
  case R.id.red:
   btn.setTextColor(Color.RED);
   return true;
  case R.id.blue:
   btn.setTextColor(Color.BLUE);
   return true;
  case R.id.green:
   btn.setTextColor(Color.GREEN);
   return true;
  }
  return false;
 }

이 코드를 실행하면 서브 메뉴 선택에 따라서 버튼에 대한 상태가 바뀜을 확인 할 수 있다.