如何解决如何在 Android 的操作栏中自定义扩展的 SearchView?
在 ActionBar 中展开时的默认 SearchView 如下图所示:
我想自定义与此图像类似的扩展 SearchView :
我是 Android 开发的新手。如果有人能帮助我,我将不胜感激。
解决方法
SearchView for Androidx 包由 EditText 和一些 AppCompatImageView 组成,例如关闭图标和搜索图标
要自定义它,您必须访问我已经讨论过的这些视图
例如,要像您展示的图像一样更改背景,您需要创建一个像 belew 的形状:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#02B15D" />
<corners android:radius="15dp" />
<stroke
android:width="2dp"
android:color="#1A40FF" />
</shape>
这是它的形状:
上面的形状你必须把它添加到EditText
的背景中要获得此 EditText 很简单,只需在您身上使用它 onCreateOptionMenu
:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu,menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
EditText editText = (searchView.findViewById(androidx.appcompat.R.id.search_src_text)); // get the EditText from it
editText.setBackgroundResource(R.drawable.round_search); // set the background to searchView
// you can do more with the editText like textColor hint color .....
return super.onCreateOptionsMenu(menu);
}
要自定义搜索图标,请使用此
AppCompatImageView searchIcon = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon);
对于显示工具栏的搜索按钮,请使用:
AppCompatImageView search_button = searchView.findViewById(androidx.appcompat.R.id.search_button);
最后关闭按钮使用这个:
AppCompatImageView search_close_btn = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
结果如下:
更新
要使 SearchView 左侧的搜索图标可见,您可以使用此方法向 EditText 添加一个图标:
editText.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.ic_menu_search,0);
如果你使用:
AppCompatImageView searchIcon = searchView.findViewById(androidx.appcompat.R.id.search_mag_icon); searchIcon.setImageResource(android.R.drawable.ic_menu_search);
您必须添加 searchView.setIconifiedByDefault(false);
但图标在形状外可见,请参见下图:
所以如果你想要形状内的图标使用第一种方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。