android - 如何创建自定义 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>
关于我做错了什么的任何想法?我的任何其他自定义偏好都没有这个问题。
解决方案
问题似乎是,除了我的自定义布局需要标记的 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
为隐藏它。
推荐阅读
- visual-studio-code - 更漂亮的扩展在 Linux Ubuntu 上没有工作
- php - Laravel 7 - 返回父菜单
- rust - 从 Rust 调用 OpenACC 代码不在 GPU 上运行
- android - 从 Android 设备通过 Firebase 发送推送通知
- python - Django 不渲染图像
- redis - 如何从 Redis 信息中解释“evicted_keys”
- c# - SSRS 客户端证书自定义身份验证
- r - 使用 rvest 提取页面抓取标题的问题
- graph - 如何以 json 格式返回所有子图?
- php - 在 TCPDF html 表中获取二维条码