【发布时间】:2020-11-18 16:40:47
【问题描述】:
我想创建一个如下图所示的搜索框。我知道我应该创建一个圆形的编辑文本,但我不知道,我应该在右侧添加红色搜索图像和imageView,或者我可以将它设置为edittext 右侧的可绘制对象,或者我可以做其他事情。
【问题讨论】:
标签: android user-interface android-edittext uisearchbar
我想创建一个如下图所示的搜索框。我知道我应该创建一个圆形的编辑文本,但我不知道,我应该在右侧添加红色搜索图像和imageView,或者我可以将它设置为edittext 右侧的可绘制对象,或者我可以做其他事情。
【问题讨论】:
标签: android user-interface android-edittext uisearchbar
设置drawable,你可能得不到想要的结果。所以使用 ImageView 将是一个不错的选择。代码如下-
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/search_bar_bg"
android:hint="Search..."
android:padding="8dp" />
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="end"
android:background="@drawable/search_img_bg"
android:scaleType="centerInside"
android:src="@drawable/ic_find" />
</FrameLayout>
search_bar_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<corners android:radius="31dp"/>
</shape>
search_img_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#E06E6E"/>
<corners android:topRightRadius="31dp" android:bottomRightRadius="31dp"/>
</shape>
上面代码的结果
编码愉快!!
【讨论】:
这是使用SearchView实现此目的的最佳方法
<LinearLayout
android:layout_width="match_parent"
android:background="@drawable/search_bar_background"
android:layout_height="wrap_content">
<androidx.appcompat.widget.SearchView
style="@style/MySearchView"
android:id="@+id/search_bar"
app:defaultQueryHint="Search..."
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"/>
<ImageView
android:background="@drawable/search_icon_background"
android:layout_width="60dp"
android:src="@drawable/ic_search"
android:padding="10dp"
android:layout_height="match_parent"/>
</LinearLayout>
现在在style.xml
<style name="MySearchView" parent="Widget.AppCompat.SearchView.ActionBar">
<item name="searchHintIcon">@null</item>
<item name="queryBackground">@null</item>
<item name="searchIcon">@null</item>
</style>
可绘制search_bar_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff"/>
<stroke android:width="1dp" android:color="#e5e5e5"/>
<corners android:radius="25dp"/>
</shape>
可绘制search_icon_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FA6A64"/>
<corners android:topRightRadius="25dp"
android:bottomRightRadius="25dp"/>
</shape>
**输出:**
您还可以通过添加selector 或ripple 来更新可绘制文件。
注意:SearchView 不支持 drawableRight。
【讨论】: