【发布时间】:2020-05-16 17:15:10
【问题描述】:
【问题讨论】:
-
您想在 java 中而不是 XML 中创建搜索视图?
-
当然是 XML。但是 Java 也需要一些配置。
标签: java android searchview
【问题讨论】:
标签: java android searchview
您在图片中看到的是材质TextInput 和OutLined 样式。你可以在官方文档here 中阅读更多关于它和Filled 风格的信息。
另外,不要忘记为此您需要材料库。为此,做
implementation 'com.google.android.material:material:1.2.0-alpha06'
现在,您可以通过添加startDrawable 和CornerRadius 使其与上面一样:
如下创建 XML 小部件并放置 startIcon。
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/editTextLayout"
style="@style/TextInputLayoutAppearanceOutLined"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="Search View"
app:hintEnabled="true"
app:startIconDrawable=" *** Your ICON *** ">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:textSize="12sp" />
</com.google.android.material.textfield.TextInputLayout>
那么,这就是TextInputLayoutAppearanceOutLined的样式,放到你的style.xml文件中:
<style name="TextInputLayoutAppearanceOutLined" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<item name="hintTextAppearance">@style/HintText</item>
<item name="helperTextTextAppearance">@style/HintText</item>
<item name="android:textColor">@color/dark_grey</item>
<item name="android:textColorHint">@color/colorAccent</item>
<item name="hintTextColor">@color/colorAccent</item>
<item name="boxStrokeColor">@color/colorAccent</item>
<item name="startIconTint">@color/colorAccent</item>
<item name="boxBackgroundColor">@color/white</item>
<item name="boxCornerRadiusBottomEnd">@dimen/_26sdp</item>
<item name="boxCornerRadiusBottomStart">@dimen/_26sdp</item>
<item name="boxCornerRadiusTopEnd">@dimen/_26sdp</item>
<item name="boxCornerRadiusTopStart">@dimen/_26sdp</item>
<item name="boxStrokeWidthFocused">1dp</item>
<item name="hintEnabled">true</item>
<item name="hintAnimationEnabled">true</item>
<item name="colorControlNormal">@color/colorAccent</item>
<item name="colorControlActivated">@color/colorPrimary</item>
显然,您也可以在 XML 中设置它,但样式可以让您更好地控制您的应用,通过一次编辑即可更改任何地方的元素。
SearchView 的外观,但要进一步使其表现得像 SearchView,您需要为您的 ListAdapter 设置过滤以使其正常工作。为此,您可以查看here。
【讨论】:
首先在布局文件中创建搜索视图
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_round"/>
然后制作drawable并将其命名为bg_round并将下面的代码放入该drawable
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#fff"/> // this the the inner background color
<stroke android:width="5dp" //this is for the stroke of the border
android:color="@android:color/black"/> //this is the stroke color
<corners android:radius="4cdp" /> //this is the corner radius
</shape>
【讨论】: