首页 > 解决方案 > 如何创建自定义 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)

当我尝试访问设置时。原因似乎是它找不到我的自定义搜索栏元素并将其链接到首选项。通常我会将自定义首选项元素命名为类似于@android:id/seekbar使链接起作用的名称,但是当涉及到 SeekBar 时,它表示这是私有的。我@+id/seekbar按照Android: Creating custom preference进行了尝试,但似乎无法将我的自定义搜索栏与偏好联系起来。

这是我的代码:

偏好 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>

关于我做错了什么的任何想法?我的任何其他自定义偏好都没有这个问题。

标签: androidlayoutsharedpreferencesandroid-support-libraryseekbar

解决方案


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

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

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


推荐阅读