以编程方式更改ScrollView的颜色

13

我目前在做什么

目前,我使用 android:scrollbarThumbVertical 属性在我的 XML 文件中更改了滚动条,如下所示:

<ScrollView
    android:id="@+id/scrollView1"
    android:scrollbarThumbVertical="@drawable/scrollbar_blue"
    ... >

scrollbar_blue 是指我的 scrollbar_blue.xml 文件,其内容如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <gradient
        android:angle="45"
        android:centerColor="@color/blue"
        android:endColor="@color/blue"
        android:startColor="@color/blue" />

    <corners android:radius="8dp" />
</shape>

我想做什么

我在我的应用程序中有一个颜色选项-所以当颜色为蓝色时,它应该保持蓝色;否则,它应该是灰色。

如何以编程方式(在我的活动类中)更改我的ScrollView以使用我的scrollbar_grey.xml

如果您查看Android文档的ScrollView,则没有相应的方法可以使用android:scrollbarThumbVertical

我也可以接受其他更改颜色的方法。

这是我创建对我的ScrollView引用的方式:

ScrollView scr = (ScrollView)findViewById(R.id.scrollView1);

尝试使用以下代码:scr.setBackgroundResource(R.drawable.yourstylexml) - mohammed momn
@mohammedmomn 这不会改变滚动条的颜色,它会改变整个滚动视图的颜色。感谢你尝试了一些东西。 - Michael Yaworski
4个回答

28

有一种方法可以通过编程来改变它,但是这种方法没有公开。从我所读的内容来看,似乎没有其他可编程更改的内容。

然而,我找到了一个stackoverflow答案,使用反射来实现它。 如果这个答案对您有用,请在那里点赞:https://dev59.com/W2kw5IYBdhLWcg3wrsrn#19819843

这个答案是针对listview的,但对于scrollview同样适用:

ScrollView scr = (ScrollView)findViewById(R.id.scrollView1);
try
{
    Field mScrollCacheField = View.class.getDeclaredField("mScrollCache");
    mScrollCacheField.setAccessible(true);
    Object mScrollCache = mScrollCacheField.get(scr); // scr is your Scroll View

    Field scrollBarField = mScrollCache.getClass().getDeclaredField("scrollBar");
    scrollBarField.setAccessible(true);
    Object scrollBar = scrollBarField.get(mScrollCache);

    Method method = scrollBar.getClass().getDeclaredMethod("setVerticalThumbDrawable", Drawable.class);
    method.setAccessible(true);

    // Set your drawable here.
    method.invoke(scrollBar, getResources().getDrawable(R.drawable.scrollbar_blue));
}
catch(Exception e)
{
    e.printStackTrace();
}

我找到的唯一东西,我自己尝试了一下,它有效。


4
好的回答(特别是有源头)!顺便提一下:安卓没有明确的方法做这件事情,真的很荒谬。 - Michael Yaworski

1
在API 29+中使用ScrollView.setVerticalScrollbarThumbDrawable(),否则使用被接受的答案。

0

此方法需要API 29或更高版本:

public static void changeBarColor(ScrollView sv, int thumbColor,int trackColor) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        sv.getVerticalScrollbarThumbDrawable().setTint(thumbColor);
        sv.getVerticalScrollbarTrackDrawable().setTint(trackColor);
    }
}

enter image description here


0

现在很容易 :)

scrollView.verticalScrollbarThumbDrawable = ColorDrawable(Color.CYAN)
scrollView.horizontalScrollbarThumbDrawable = ColorDrawable(Color.WHITE)

需要最低API 29,是的。 - ucMedia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接