'Adding vertical scrollbar to EditText programmatically in Android?
I am trying to add a vertical scrollbar to an EditText programmatically. If I use it in XML, it works well. Unfortunately I get a Null Pointer Exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.widget.ScrollBarDrawable android.widget.ScrollBarDrawable.mutate()' on a null object reference
at android.view.View.onDrawScrollBars(View.java:21272)
The error is caused by the call of setScrollbarFadingEnabled.
inputField.setVerticalScrollBarEnabled(true);
inputField.setScrollbarFadingEnabled(false);
The EditText is generated programmatically and does work well without the function call. Do you have any idea how to fix it? Is the view not updated or what might cause this error?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zain |
