Android开发实现圆角搜索框

1.在 res/values/colors.xml中增加 <color name="grey">#F3EDED</color> 作为填充色。
然后 res/drawable 文件夹下新建 bg_searchview.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 圆角度 -->
    <corners android:radius="35dp"/>
    <!-- 使用填充色 -->
    <solid android:color="@color/grey"/>
</shape>

2.在布局文件中使用 SearchView 搜索组件,并使用上面的 bg_searchview.xml 来设置圆角和填充色:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/bg_searchview"
        android:iconifiedByDefault="false"
        android:imeOptions="actionSearch"
        android:queryBackground="@drawable/bg_searchview"
        android:queryHint="搜索"
        android:submitBackground="@drawable/bg_searchview"
        app:theme="@style/AppSearchView" />
</LinearLayout>

效果如下:
在这里插入图片描述

4.如果你想让搜索框中的搜索提示语居中,可以在res/values文件夹下新增 styles.xml 文件:

<resources>
    <style name="AppSearchView" parent="Widget.AppCompat.SearchView" >
        <item name="android:textAlignment">center</item>
    </style>
</resources>

在布局文件中的 SearchView 搜索组件中使用 app:theme="@style/AppSearchView" 来居中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <SearchView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/bg_searchview"
        android:iconifiedByDefault="false"
        android:imeOptions="actionSearch"
        android:queryBackground="@drawable/bg_searchview"
        android:queryHint="搜索"
        android:submitBackground="@drawable/bg_searchview"
        app:theme="@style/AppSearchView"
 />
</LinearLayout>

效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_33697094/article/details/131126131
今日推荐