解決某些機型中EditText無法修改光標以及光標不展示問題
產(chǎn)生原因:
1.某些機型光標默認是白色 當EditText是白色背景的時候會導(dǎo)致光標展示不出來
2.光標設(shè)置了默認不展示也會導(dǎo)致光標展示不出來
3.某些機型修改了系統(tǒng)方法引發(fā)的光標展示不出來
解決方案:
1.1 textCursorDrawable :設(shè)置光標資源文件的方法(注意這是個drawable文件夾下的一個資源文件)
<!-- Reference to a drawable that will be drawn under the insertion cursor. -->
<!-- 翻譯:對將在插入光標下繪制的可繪制圖形的引用-->
<attr name="textCursorDrawable" format="reference" />

設(shè)置自定義光標文件
1.2 資源文件 edit_cursor.xml文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#21BC23" />
<size android:width="1dp" />
</shape>
2.cursorVisible :設(shè)置光標默認展示不展示的方法
<!-- Makes the cursor visible (the default) or invisible. -->
<!-- 翻譯:使光標可見(默認設(shè)置)或不可見。. -->
<attr name="cursorVisible" format="boolean" />

image.png
3.有些三方嘗試修改了底層代碼導(dǎo)致獲取不到數(shù)據(jù)可嘗試反射回去然后再設(shè)置嘗試一下
public class CustomEditText extends EditText {
public GeneralEditText(Context context) {
super(context);
}
public CustomEditText (Context context, AttributeSet attrs) {
super(context, attrs);
modifyCursorDrawable(context, attrs);
}
public CustomEditText (Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
modifyCursorDrawable(context, attrs);
}
private void modifyCursorDrawable(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText);
int drawable = a.getResourceId(R.styleable.CustomEditText_textCursorDrawable, 0);
if (drawable != 0) {
try {
Field setCursor = TextView.class.getDeclaredField("mCursorDrawableRes");
setCursor.setAccessible(true);
setCursor.set(this, drawable);
} catch (Exception e) {
e.printStackTrace();
}
}
a.recycle();
}
}
3.2 attrs.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomEditText">
<attr name="textCursorDrawable" format="reference" />
</declare-styleable>
</resources>
總結(jié)
簡單總結(jié)了一下項目中兼容問題出現(xiàn)的EditText光標出現(xiàn)的問題特此記錄一下