更改EditText中光标的可绘制性



我尝试以不同的方式和顺序在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>  

cursor.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);
}          

最新更新