我只想在我的项目中包含一个SeekBarPreference,只有3个值(紧急级别:低、中、高)。
这可以很容易地在一个经典的SeekBar上完成(参见下面的示例),但我不知道如何推断这是一种偏好。
如果我使用这段代码,它将在SeekBar (不是首选项)中工作,但在Preferences中,它仍然会显示一个没有粗标记的SeekBar。
代码:
<SeekBar
android:id="@+id/sb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="10"
android:thumb="@drawable/ic_location"
android:theme="@style/Widget.AppCompat.SeekBar.Discrete" />有什么想法或建议吗?

发布于 2017-12-06 12:21:37
您需要使用支持SeekbarPreference来自定义thumb和all。您可以传递您自己的自定义布局为您的寻求酒吧首选项。请检查下面的例子。
您的活动,您将添加您的首选项片段
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BlankFragment mPrefsFragment = new BlankFragment();
FragmentManager mFragmentManager = getSupportFragmentManager();
FragmentTransaction mFragmentTransaction = mFragmentManager
.beginTransaction();
mFragmentTransaction.replace(android.R.id.content, mPrefsFragment);
mFragmentTransaction.commit();
}
}您必须在清单中为此活动添加一个特定主题,
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.SettingsTheme" />styles.xml
<style name="AppTheme.SettingsTheme" parent="AppTheme.NoActionBar">
<item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
</style>从xml加载首选项的片段
BlankFragment.java
public class BlankFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}和您的首选项文件来自 xml 文件夹。
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.preference.SeekBarPreference
android:key="your_pref_key"
android:max="3"
android:thumb="@drawable/thumb_icon"
android:summary="Summary"
android:layout="@layout/my_custom_seekbar"
android:title="Title" />
</android.support.v7.preference.PreferenceScreen>在这里,您可以看到android:layout属性接受一个资源布局文件,在该文件中您可以提供您自己的自定义查找栏和一个文本视图--它显示了从seekbar选择的值。
my_custom_seekbar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SeekBar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/seekbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/seekbar_value"
android:max="10"
android:theme="@style/Widget.AppCompat.SeekBar.Discrete"
android:thumb="@drawable/ic_location" />
<TextView
android:id="@+id/seekbar_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>注意,您必须为您的自定义NullPointerException和TextView使用完全相同的标识符,否则它将引发 SeekBar
android:id="@+id/seekbar" for your custom Seekbar
android:id="@+id/seekbar_value" for your custom TextViewhttps://stackoverflow.com/questions/47672431
复制相似问题