选项菜单
main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="AppCompatResource">
<item android:id="@+id/menu_toggle_log"
android:showAsAction="always"
android:title="@string/sample_show_log" />
</menu>
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/sample_main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ViewAnimator
android:id="@+id/sample_output"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<ScrollView
style="@style/Widget.SampleMessageTile"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
style="@style/Widget.SampleMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/vertical_page_margin"
android:paddingLeft="@dimen/horizontal_page_margin"
android:paddingRight="@dimen/horizontal_page_margin"
android:paddingTop="@dimen/vertical_page_margin"
android:text="@string/intro_message"/>
</ScrollView>
<fragment
android:id="@+id/log_fragment"
android:name="com.example.android.common.logger.LogFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</ViewAnimator>
MainActivity.java
...
private boolean mLogShown;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem logToggle = menu.findItem(R.id.menu_toggle_log);
//根据当前显示的内容是否为ViewAnimator而决定是否显示logToogle菜单
logToggle.setVisible(findViewById(R.id.sample_output) instanceof ViewAnimator);
//根据ViewAnimator显示子控件而决定logToggle显示的标题内容
logToggle.setTitle(mLogShown ? R.string.sample_hide_log : R.string.sample_show_log);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_toggle_log:
mLogShown = !mLogShown;
ViewAnimator output = (ViewAnimator) findViewById(R.id.sample_output);
if (mLogShown) {
output.setDisplayedChild(1);
} else {
output.setDisplayedChild(0);
}
//更新菜单,调用onCreateOptionsMenu与onPrepareOptionsMenu
supportInvalidateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
837

被折叠的 条评论
为什么被折叠?



