java - 在EditText中更改光标的drawable
问题描述
我尝试以不同的方式和不同的顺序更改 afterTextChanged() 中的可绘制光标。我究竟做错了什么?在 EditText 中输入字符后如何更改光标?
public class View extends ConstraintLayout {
private EditText editText;
public View (Context context, AttributeSet attrs) {
super(context, attrs);
editText = findViewById(R.id.editText);
editText.setTextCursorDrawable(R.drawable.first_cursor);
editText.setCursorVisible(true);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
editText.setCursorVisible(false);
editText.setTextCursorDrawable(null);
editText.setTextCursorDrawable(R.drawable.second_cursor);
requestLayout();
editText.invalidate();
invalidate();
editText.setCursorVisible(true);
}
在第二个光标中,我想为其设置填充。
解决方案
这对我有帮助:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/start"
android:right="16px">
<shape>
<size
android:width="4px"
android:height="64px" />
<solid android:color="@color/color1" />
<corners android:radius="4px" />
</shape>
</item>
<item
android:id="@+id/end"
android:left="@dimen/16px">
<shape>
<size
android:width="4px"
android:height="64px" />
<solid android:color="@color/color1" />
<corners android:radius="4px" />
</shape>
</item>
</layer-list>
光标.xml
public class View extends ConstraintLayout {
private EditText editText;
private boolean isVisibleLayerEnd = false;
public View (Context context, AttributeSet attrs) {
super(context, attrs);
editText = findViewById(R.id.editText);
LayerDrawable drawable = (LayerDrawable) getResources().
getDrawable(R.drawable.cursor);
Drawable layerStart = drawable.findDrawableByLayerId(R.id.start);
Drawable layerEnd = drawable.findDrawableByLayerId(R.id.end);
layerEnd.setAlpha(0);
editText.setTextCursorDrawable(drawable);
editText.setCursorVisible(true);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int count, int
after) {}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int
count) {}
@Override
public void afterTextChanged(Editable s) {
if (editText.getText().length() >= 1 && !isVisibleLayerEnd) {
layerStart.setAlpha(0);
layerEnd.setAlpha(255);
isVisibleLayerEnd = true;
}
if (mPrimaryEditText.getText().length() == 0) {
layerStart.setAlpha(255);
layerEnd.setAlpha(0);
isVisibleLayerEnd = false;
}
editText.setCursorVisible(true);
}
推荐阅读
- r - 在 R 中调用打印函数后,我的 S3 通用函数停止工作
- java - Oracle 数据库与 Android Studio 的连接
- docker - 有没有办法从 CI 过程中在 docker 容器中生成的图像中提取文件返回到 GITLAB 存储库
- python - Python Numpy 加性高斯白噪声函数
- uber-api - Ubereats:如何获取已完成订单的列表
- python - 相关矩阵不包括给定数据框中的所有特征
- javascript - 元素后的垂直菜单在悬停时移动到下一个 li 并通过平滑过渡激活
- node.js - 我可以在用户集合中查找时匹配来自 userdetail 的数组数据吗
- java - Prime faces 表格行扩展默认值
- visual-studio-code - 如何缩小此屏幕?