请引用我的项目: https://github.com/paulpv/ToolbarSwitch
我正在为 Android 工具栏(又名:新 ActionBar)开发一个简单的自定义布局。 这个简单的控件向工具栏添加了一个开关,可以在此处以洋红色突出显示:
我的问题是,当按下溢出菜单时,Switch 的文本会立即跳到工具栏的顶部,并在您关闭溢出菜单时保持原样:
类似的事情发生在横向(细微差别是溢出菜单弹出窗口没有任何顶部填充)。
我可以对菜单项的 actionLayout 做些什么来防止文本跳转?
菜单/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_switch"
android:title="@string/action_switch"
app:actionLayout="@layout/toolbar_switch"
app:showAsAction="always" />
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
布局/toolbar_switch.xml
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/action_switch"
android:text="@string/action_switch"
android:switchPadding="10dp"
android:background="#ff00ff"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
显然,我想我可以创建两个 View ,一个 TextView 和一个 Switch,我在其中分别设置 TextView 上的文本,我不直接设置 Switch 的文本...但我更愿意设置文本直接在 Switch 上。
还有几个问题:
- 当使用 ActionBarActivity 并展开工具栏菜单时,为什么在 onCreateOptionsMenu 之前调用 onResume?
- 反过来,在与#1 相同的情况下,为什么在 onCreate 和 onResume 之间没有调用 onCreateOptionsMenu?
- 在横向模式下,标题文字大小明显变小;这是预期的和可取的吗?
- 如何将横向标题文字大小设置为与纵向文字大小相同?
谢谢!
PV
最佳答案
我按照你的代码将 Switch 添加到我的操作栏,我能够通过将 Switch 的宽度设置为 wrap_content 来解决你的“跳跃文本”问题,如下所示:
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/action_switch"
android:text="@string/action_switch"
android:switchPadding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
关于Android Toolbar actionLayout of Switch导致菜单按下时文本跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664412/