Android EditText設(shè)置光標(兼容華為,榮耀,小米)

解決某些機型中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)的問題特此記錄一下

重要的事兒說三遍 點贊(1),點贊(2),點贊(3)!!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容