Android开发实现圆角搜索框

文章讲述了如何在Android应用中自定义SearchView的样式,包括在colors.xml中定义颜色,创建bg_searchview.xml设置圆角和填充色,以及在styles.xml中调整文本对齐方式,使得搜索提示语居中显示。
摘要由CSDN通过智能技术生成

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>

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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值