Android EditText获取光标时改变背景
在Android开发过程中,我们经常需要对EditText进行一些特殊的处理,比如在获取光标时改变其背景颜色。本文将介绍如何使用代码实现这一功能。
1. XML布局
首先,我们需要在XML布局文件中定义一个EditText控件,如下所示:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/edit_text_bg"
android:cursorVisible="false"
android:focusable="true"
android:gravity="center"
android:hint="点击获取焦点"
android:textColorHint="@color/colorHint" />
在上述代码中,我们通过设置android:background
属性来指定EditText的背景,这里使用了一个自定义的背景资源edit_text_bg
。同时,我们还设置了android:cursorVisible="false"
,这样在一开始时EditText中的光标是不可见的。
2. 自定义背景资源
接下来,我们需要创建一个自定义的背景资源edit_text_bg.xml
,并将其放置在res/drawable目录下。该资源文件的内容如下:
<selector xmlns:android="
<item android:drawable="@drawable/edit_text_focused" android:state_focused="true" />
<item android:drawable="@drawable/edit_text_normal" />
</selector>
上述代码中,我们使用了<selector>
标签来定义背景资源的不同状态。其中,android:drawable
属性用于指定不同状态下的背景图片,android:state_focused="true"
表示EditText获取焦点时的状态。
3. 定义背景图片
我们需要为EditText的不同状态定义不同的背景图片,这里我们创建了edit_text_focused.xml
和edit_text_normal.xml
两个资源文件,并将其放置在res/drawable目录下。这两个资源文件的内容如下:
<!--edit_text_focused.xml-->
<shape xmlns:android="
<solid android:color="@color/colorFocused" />
<corners android:radius="10dp" />
</shape>
<!--edit_text_normal.xml-->
<shape xmlns:android="
<solid android:color="@color/colorNormal" />
<corners android:radius="10dp" />
</shape>
上述代码中,我们使用了<shape>
标签来定义背景形状,<solid>
标签用于填充背景颜色,<corners>
标签指定了矩形的圆角半径。我们可以根据需求修改背景颜色和圆角半径。
4. Java代码实现
现在,我们需要在Java代码中实现获取光标时改变EditText背景的功能。首先,在Activity的onCreate
方法中获取EditText控件的实例:
EditText editText = findViewById(R.id.editText);
接下来,我们需要为EditText设置焦点变化的监听器,代码如下:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
editText.setBackgroundResource(R.drawable.edit_text_focused);
} else {
editText.setBackgroundResource(R.drawable.edit_text_normal);
}
}
});
在上述代码中,我们使用setOnFocusChangeListener
方法为EditText设置焦点变化的监听器。当EditText获取焦点时,hasFocus
参数为true
,我们将其背景设置为获取焦点时的背景资源;当EditText失去焦点时,hasFocus
参数为false
,我们将其背景设置为正常状态下的背景资源。
5. 效果演示
以下是通过实现上述代码后的效果演示:
gantt
dateFormat YYYY-MM-DD
title EditText获取光标时改变背景效果演示
section 预处理
创建XML布局文件 : done, 2022-07-01, 1d
自定义背景资源 : done, 2022-07-02, 1d
定义背景图片 : done, 2022