带回调的OnPreferenceChangeListener

时间:2018-02-07 07:27:55

标签: android

在“首选项”屏幕中,我有一个CheckBoxPreference 我在这个复选框中添加了一个OnPreferenceChangeListener`。

当我需要检查某些权限是否被授予时打开/关闭它。 但是Ripple效应仍然存在于API 21中。

myPreference = (CheckBoxPreference)findPreference("my_pref");
myPreference.setLayoutResource(R.layout.preference_list_checkbox);
myPreference.setOnPreferenceChangeListener(onPressed);

CheckBoxPreference.OnPreferenceChangeListener onPressed = new CheckBoxPreference.OnPreferenceChangeListener() {

    @Override
public boolean onPreferenceChange(final Preference preference, Object newValue) {
        final boolean isCheckedNow = Boolean.valueOf(newValue.toString());

        util.checkPermissionGranted(new CallbackParam<Boolean>() {
            @Override
            public void callback(Boolean onPermissionGranted) {
                if(onPermissionGranted){
                    // Call service
                }else{
                    myPreference.setChecked(false);
                }
            }
        });

        return true;
    }
};



<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:paddingTop="4dp"
    android:paddingBottom="6dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:gravity="center_vertical">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <TextView
            android:id="@android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textColor="@color/settings_titlebar_color"
            android:textSize="17sp"
            android:textStyle="bold"
            tools:text="Test" />

        <TextView
            android:id="@android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:maxLines="4"
            android:textAppearance="?android:attr/textAppearanceSmall"
            tools:text="Test" />

    </LinearLayout>

    <!-- Preference should place its actual preference widget here. -->
    <LinearLayout android:id="@android:id/widget_frame"
        android:layout_width="wrap_content" android:layout_height="match_parent"
        android:gravity="center_vertical" android:orientation="vertical" />

</LinearLayout>

我认为问题是因为我在短寿命方法中使用回调。但是,我该如何解决呢?

enter image description here

有什么建议吗?谢谢!

0 个答案:

没有答案