我只是想在我的项目中包含一个只有3个值的SeekBarPreference(紧急程度:低 – 中 – 高)

这可以很容易地在经典的SeekBar上完成(参见下面的示例),但我不知道如何能够包含偏好.

如果我使用这个代码,它将在SeekBar(不是Preference)中工作,但在Preferences中它仍然会显示没有粗标记的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" />

有什么想法或建议吗?

48f3c775eb9901d5c766903c5f3f19b8.gif

解决方法:

您需要使用支持SeekbarPreference来自定义拇指和所有.您可以为自己的搜索栏偏好传递自己的自定义布局.请查看下面的示例.

您的活动,您将添加您的偏好片段

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();

}

}

您必须在清单中为此活动添加特定主题

android:name=".MainActivity"

android:theme="@style/AppTheme.SettingsTheme" />

styles.xml

@style/PreferenceThemeOverlay

从xml加载首选项的片段

BlankFragment.java

public class BlankFragment extends PreferenceFragmentCompat {

@Override

public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {

setPreferencesFromResource(R.xml.preferences, rootKey);

}

}

您的首选项文件来自xml res文件夹

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:layout属性采用资源布局文件,您可以在其中提供自己的自定义搜索栏和textview,其中显示了搜索栏中的选定值

my_custom_seekbar.xml

android:layout_width="match_parent"

android:layout_height="match_parent">

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" />

android:id="@+id/seekbar_value"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignParentRight="true" />

请注意,您必须为自定义使用完全相同的标识符

SeekBar和TextView,否则会抛出NullPointerException

android:id="@+id/seekbar" for your custom Seekbar

android:id="@+id/seekbar_value" for your custom TextView

标签:android,android-preferences,seekbarpreference

来源: https://codeday.me/bug/20190705/1389706.html

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐