在不使用库的情况下,可以通过自定义形状来同时在聚焦状态和正常状态下应用TextInputLayout。
首先,需要在布局文件中使用TextInputLayout和TextInputEditText来创建输入框。然后,通过设置TextInputLayout的background属性来定义输入框的背景形状。
在聚焦状态下,可以使用XML的selector来定义不同状态下的背景形状。创建一个名为"custom_text_input_layout_focused.xml"的文件,内容如下:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape android:shape="rectangle">
<!-- 自定义聚焦状态下的背景形状 -->
<!-- 可以设置边框颜色、边框宽度、背景颜色等 -->
</shape>
</item>
<item>
<shape android:shape="rectangle">
<!-- 自定义正常状态下的背景形状 -->
<!-- 可以设置边框颜色、边框宽度、背景颜色等 -->
</shape>
</item>
</selector>
然后,在TextInputLayout中引用这个selector文件作为背景,如下所示:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/custom_text_input_layout_focused">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/text_input_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入内容" />
</com.google.android.material.textfield.TextInputLayout>
这样,当输入框处于聚焦状态时,会应用"custom_text_input_layout_focused.xml"中定义的聚焦状态下的背景形状;当输入框处于正常状态时,会应用"custom_text_input_layout_focused.xml"中定义的正常状态下的背景形状。
注意:以上示例中使用了Google的Material Design库中的TextInputLayout和TextInputEditText,如果不使用库,可以自行实现类似的效果。
领取专属 10元无门槛券
手把手带您无忧上云