Cause:
Turns out that the NPE is raised as ScrollBarDrawable is null; this is the scrollbarThumbVertical of the EditText scrollbar.
Enabling scrollbars programmatically with setVerticalScrollBarEnabled(true) seems to have no affect, and therefore calling setScrollbarFadingEnabled() raises this error.
Solution
Option 1:
Enable the scrollbars in XML as a style, and set the style to the EditText using a wrapper
Create the below style:
<style name="scrollbar_style">
<item name="android:scrollbars">vertical</item>
</style>
Apply the style to the EditText:
EditText inputField = EditText(ContextThemeWrapper(context, R.style.scrollbar_style));
Option 2:
Create a template EditText that has a predefined scrollbars, and inflate it instead of creating an EditText.
edidtext.xml:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
EditText inputField =
inflater.inflate(R.layout.edittext, myRootLayout, false);
inputField.setVerticalScrollBarEnabled(true);
inputField.setScrollbarFadingEnabled(false);
Option 3:
If you are targeting API level 29+, then you can use setVerticalScrollbarThumbDrawable to set a predefined thumbnail:
inputField.setVerticalScrollbarThumbDrawable(
ResourcesCompat.getDrawable(getResources(),
R.drawable.scrollview_thumb, null));
scrollview_thumb:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#BDBBBB" />
<size android:width="3dp" />
</shape>
- Option 1 is flexible for a wide range of API levels.
- Option 2 is not that elegant solution; but probably can help in other cases.
- Option 3 requires to override the default scrollbar thumbnail, and available from API level 29.