如何创建自定义SeekBar首选项?

时间:2019-04-06 08:15:44

标签: android layout sharedpreferences android-support-library seekbar

我正在尝试创建自定义的搜索栏首选项,但是Android似乎找不到该元素。我得到

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference at
    at android.support.v7.preference.SeekBarPreference.onBindViewHolder(SeekBarPreference.java:154)

当我尝试访问设置时。原因似乎是它找不到我的自定义seekbar元素并将其链接到首选项。通常,我会给自定义首选项元素命名为@android:id/seekbar之类的名称,以使链接起作用,但是对于SeekBar,它说这是私有的。我按照Android: Creating custom preference尝试了@+id/seekbar,但是将自定义搜索栏与首选项绑定似乎无效。

这是我的代码:

首选项XML

<android.support.v7.preference.SeekBarPreference
            android:key="my_seekbar_preference"
            android:layout="@layout/seekbar_preference"
            android:max="10"
            android:defaultValue="5" />

SeekBar布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="@dimen/half_normal">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/half_normal"
    android:layout_marginLeft="@dimen/normal"
    style="@style/SettingsSubHeader"
    android:text="Seekbar Settings"/>

<SeekBar
    android:id="@+id/seekbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/Widget.AppCompat.SeekBar.Discrete"
    android:max="10"
    android:min="0"/>

</LinearLayout>

关于我在做什么错的任何想法?我的其他自定义首选项都没有这个问题。

1 个答案:

答案 0 :(得分:0)

问题似乎是,除了我的自定义布局需要一个标记为@+id/seekbar的Seekbar元素外,还需要一个标记为@+id/seekbar_value的Textview元素来显示该搜索条的当前值。如果缺少此方法,则会得到一个空指针异常。如果我添加一个,一切正常:

<TextView
    android:id="@+id/seekbar_value"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

还要注意,设置android:visibility="gone"在这种情况下不起作用,因此,如果您不想显示该值,则需要设置android:textSize="0dp使其隐藏。

相关问题