我正在尝试将SearchView移动到工具栏右侧,但它无法正常工作。以下是我在onCreateOptionsMenu
中设置对齐的方法:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchViewItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchViewItem.getActionView();
searchView.setIconifiedByDefault(false);
searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.RIGHT));
return true;
}
menu.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_search"
android:title="@string/action_search"
android:orderInCategory="100"
android:icon="@mipmap/ic_action_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
这是一个演示图像,显示了SearchView当前的显示方式: