mercredi 14 novembre 2018

Attribute of Editor class in Android can't be found through reflection

I'm using an emulator with Android API 28 x86, and my project target/compile SDK version is 28. With this in mind, I can proceed to the real problem.

I'm trying to change the color of the EditText cursor at runtime using reflection. Looking through the SDK 28 files, I found the name of the Field that I want to change, and it is "mDrawableForCursor", this field exists inside of the Editor class. I don't know why, but this class can't be referred to my project, but that's not a problem, I can get a reference of it through reflection too. So, I wrote the following code

    // Get the cursor resource id
    Field field = TextView.class.getDeclaredField("mCursorDrawableRes");
    field.setAccessible(true);
    int drawableResId = field.getInt(this._inputEditText);
    field.setAccessible(false);

    // Get the editor
    field = TextView.class.getDeclaredField("mEditor");
    field.setAccessible(true);
    Object editor = field.get(this._inputEditText);
    field.setAccessible(false);

    // Get the drawable and set a color filter
    Drawable cursorPipe = ContextCompat.getDrawable(getContext(), drawableResId);
    cursorPipe.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    Drawable[] drawables = {cursorPipe, cursorPipe};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        field = editor.getClass().getDeclaredField("mDrawableForCursor"); // error
    } else {
        field = editor.getClass().getDeclaredField("mCursorDrawable");
    }

Now, weird things start to happen... I put one breakpoint at Editor object, and found that field exist in there (the last one), but when my code try to get this field by the method getDeclaredField(), an Exception is thrown

No field mDrawableForCursor in class Landroid/widget/Editor; (declaration of 'android.widget.Editor' appears in /system/framework/framework.jar!classes2.dex)

editor debugging

Just for curiosity, I got all declared fields of this Editor class and it seems to have only eight available, and now I have no idea of what is happening in my code. enter image description here





Aucun commentaire:

Enregistrer un commentaire