androidでオプションメニューの表示の切り替え
androidの画面でアイコンとか出せるけど任意で表示を切り替えたい。
メニュー自体はアクティビティとかで任意に変化できるけど表示するしないの切り替えは知らなかった
実装
activity_main.xml
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="チェック押下でメニューの表示を切り替え" android:id="@+id/text2" android:layout_alignParentTop="true" android:layout_alignParentStart="true" android:layout_alignParentEnd="true" /> <CheckBox android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切り替え" android:id="@+id/check1" android:layout_below="@+id/text2" android:layout_alignParentStart="true" /> </RelativeLayout>
MainActivity
package jp.mshige1979.app.samplemenu02; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; public class MainActivity extends Activity { private TextView text2 = null; private CheckBox check1 = null; private boolean checked = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // UIのIDを取得 text2 = (TextView)findViewById(R.id.text2); check1 = (CheckBox)findViewById(R.id.check1); // UIのイベントを設定 check1.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){ @Override public void onCheckedChanged(CompoundButton var1, boolean var2){ // チェック時はtrue、未チェック時はfalse checked = var2; Log.d("sample", String.valueOf(checked)); // オプションメニューを書き換える invalidateOptionsMenu(); } }); // オプションメニューの初期表示 checked = true; // 画面にチェック有無を設定 check1.setChecked(checked); } @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; } @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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // なんかこれで表示有無を切り替える return checked; } }
画面
初回
チェック切り替え後