Android PreferenceScreen

 https://blog.csdn.net/weixin_43529377/article/details/98963095

PreferenceScreen和fragment结合

获取PreferenceScreen 的上下文

final Context context = pref.getContext();  

一、监听事件

1.1、onPreferenceChange

public boolean onPreferenceChange(Preference preference, Object objValue) { return false; } 

说 明: 当Preference的元素值发送改变时,触发该事件。
返回值: true 代表将新值写入sharedPreference文件中。
false 则不将新值写入sharedPreference文件。

1.2、onPreferenceClick

public boolean onPreferenceClick(Preference preference) { return false; }

说明:当点击控件时触发发生,可以做相应操作。
参数说明: preference 点击的对象。
返回值:true,不执行onPreferenceTreeClick

1.3、onPreferenceTreeClick

public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
      return super.onPreferenceTreeClick(preferenceScreen, preference);
}

说 明: 当Preference控件被点击时,触发该方法。
参数说明: preference 点击的对象。
返 回 值: true 代表点击事件已成功捕捉,无须执行默认动作或返回上层调用链。 例如, 不跳转至默认Intent。
false 代表执行默认动作并且返回上层调用链。例如,跳转至默认Intent。

1.4、点击某个Preference控件后,会先回调onPreferenceChange()方法,即是否保存值,
然后再回调onPreferenceClick以及onPreferenceTreeClick()方法,因此在onPreferenceClick和onPreferenceTreeClick方法中我们得到的控件值就是最新的Preference控件值。

二、daemo

2.1、activity_main.xml

<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="match_parent"
    android:orientation="vertical"
    tools:context="com.gatsby.preferencesreen.MainActivity" >

    <fragment
        android:id="@+id/settingsFragment"
        android:name="com.gatsby.preferencesreen.MainActivity$SettingsFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>  

2.2、R.xml.preferences

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <PreferenceCategory android:title="标题--开关按钮" >
        <CheckBoxPreference
            android:key="checkbox_preference"
            android:summary="这是一个开关按钮"
            android:title="开关偏好" />
    </PreferenceCategory>
    <PreferenceCategory android:title="自定义偏好" >
        <Preference
            android:key="preference"
            android:summary="这是一个自定义按钮"
            android:title="自定义" />
    </PreferenceCategory>

</PreferenceScreen>  

2.3、MainActivity.java

package com.gatsby.preferencesreen;

import android.app.Activity;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.util.Log;

public class MainActivity extends Activity {

	private static final String KEY_CHECKBOX = "checkbox_preference";
	private static final String KEY_PREFERENCE = "preference";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public static class SettingsFragment extends PreferenceFragment
			implements OnPreferenceChangeListener, OnPreferenceClickListener {

		CheckBoxPreference checkbox_preference;
		Preference preference;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			addPreferencesFromResource(R.xml.preferences);

			checkbox_preference = (CheckBoxPreference) findPreference(KEY_CHECKBOX);
			checkbox_preference.setOnPreferenceChangeListener(this);
			preference = (Preference) findPreference(KEY_PREFERENCE);
			preference.setOnPreferenceClickListener(this);
		}

		@Override
		public boolean onPreferenceChange(Preference preference, Object objValue) {
			// TODO Auto-generated method stub
			final String key = preference.getKey();

			if (KEY_CHECKBOX.equals(key)) {
				boolean isCheck = (Boolean) objValue;
				if (isCheck) {
					Log.d("gatsby", "isCheck");
				} else {
					Log.d("gatsby", "not Check");
				}
			}
			return true;
		}

		@Override
		public boolean onPreferenceClick(Preference preference) {
			// TODO Auto-generated method stub
			final String key = preference.getKey();

			if (KEY_PREFERENCE.equals(key)) {
				Log.d("gatsby", "preference");
			}
			return false;
		}
		
		@Override
		public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
			// TODO Auto-generated method stub
			final String key = preference.getKey();

			if (KEY_PREFERENCE.equals(key)) {
				Log.d("gatsby", "preference TreeClick!");
			}
			return super.onPreferenceTreeClick(preferenceScreen, preference);
		}

	}
}

二. ndroid7.1 删除Preference

    <PreferenceCategory android:key="debug_networking_category"
            android:title="@string/debug_networking_category">

        <SwitchPreference
            android:key="wifi_display_certification"
            android:title="@string/wifi_display_certification"
            android:summary="@string/wifi_display_certification_summary"/>

        <ListPreference
            android:key="select_usb_configuration"
            android:title="@string/select_usb_configuration_title"
            android:dialogTitle="@string/select_usb_configuration_dialog_title"
            android:entries="@array/usb_configuration_titles"
            android:entryValues="@array/usb_configuration_values" />

        <SwitchPreference
            android:key="bluetooth_disable_absolute_volume"
            android:title="@string/bluetooth_disable_absolute_volume"
            android:summary="@string/bluetooth_disable_absolute_volume_summary"/>
    </PreferenceCategory>

 2.1.删除PreferenceCategory

		final PreferenceGroup debugNetworkingCategory = (PreferenceGroup)
                findPreference(DEBUG_NETWORKING_CATEGORY_KEY);			
		debugNetworkingCategory.removePreference(mWifiDisplayCertification);//1
                getPreferenceScreen().removePreference(debugNetworkingCategory);

 三.ListPreference

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="flight_option_preference"   按:可以通过key来获取preference,类似于view的android:id 
    android:title="My Preferences"                 按:对于最top的PreferenceScreen,此为Activity的title
    android:summary="设置航线排序选项">
    <ListPreference android:key="selected_flight_sort_option"   按:可以通过key来获取preference
        android:title="Flight Options"              
        android:summary="Set Search Options"
        android:entries="@array/flight_sort_options"                    按:list的内容
        android:entryValues="@array/flight_sort_options_values" 按:list各内容对应的value
        android:dialogTitle="Choose Flight Options"
        android:defaultValue="1"/>  <!-- 对应为entryValues的值,缺省1,即缺省为Number of Stops。 -->
</PreferenceScreen>

 四.Preferences    OnPreferenceClickListener

4.0. Preference 布局

--- a/packages/apps/Settings/res/xml/privacy_settings.xml
+++ b/packages/apps/Settings/res/xml/privacy_settings.xml
@@ -64,5 +64,16 @@
             android:fragment="com.android.settings.MasterClear" />
 
     </PreferenceCategory>
+    
+    <PreferenceCategory android:key="reboot_loader_category"
+            android:title="@string/reboot_loader_section_title">
+
+        <!-- Reboot Loader -->
+        <Preference
+	    android:key="reboot_loader_key"	
+            android:title="@string/reboot_loader_title"
+            android:summary="@string/reboot_loaderr_summary"/>
+
+    </PreferenceCategory>    
 
 </PreferenceScreen> 

4.1.Android5.1 内部类 OnPreferenceClickListener preferenceClickListener = new OnPreferenceClickListener()

--- a/packages/apps/Settings/src/com/android/settings/PrivacySettings.java
+++ b/packages/apps/Settings/src/com/android/settings/PrivacySettings.java
@@ -32,11 +32,14 @@ import android.os.UserManager;
 import android.preference.Preference;
 import android.preference.PreferenceCategory;
 import android.preference.Preference.OnPreferenceChangeListener;
+import android.preference.Preference.OnPreferenceClickListener;
 import android.preference.PreferenceScreen;
 import android.preference.SwitchPreference;
 import android.provider.SearchIndexableResource;
 import android.provider.Settings;
 import android.util.Log;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
 
 import com.android.settings.search.BaseSearchIndexProvider;
 import com.android.settings.search.Indexable;
@@ -59,6 +62,7 @@ public class PrivacySettings extends SettingsPreferenceFragment implements
     private static final String CONFIGURE_ACCOUNT = "configure_account";
     private static final String BACKUP_INACTIVE = "backup_inactive";
     private static final String PERSONAL_DATA_CATEGORY = "personal_data_category";
+	private static final String REBOOT_LOADER_KEY = "reboot_loader_key";
     private static final String TAG = "PrivacySettings";
     private IBackupManager mBackupManager;
     private SwitchPreference mBackup;
@@ -66,6 +70,7 @@ public class PrivacySettings extends SettingsPreferenceFragment implements
     private Dialog mConfirmDialog;
     private PreferenceScreen mConfigure;
     private boolean mEnabled;
+	private Preference mRebootloader;	
 
     private static final int DIALOG_ERASE_BACKUP = 2;
     private int mDialogType;
@@ -91,6 +96,9 @@ public class PrivacySettings extends SettingsPreferenceFragment implements
         mAutoRestore.setOnPreferenceChangeListener(preferenceChangeListener);
 
         mConfigure = (PreferenceScreen) screen.findPreference(CONFIGURE_ACCOUNT);
+		
+		mRebootloader = (Preference) findPreference(REBOOT_LOADER_KEY);
+		mRebootloader.setOnPreferenceClickListener(preferenceClickListener);
 
         ArrayList<String> keysToRemove = getNonVisibleKeys(getActivity());
         final int screenPreferenceCount = screen.getPreferenceCount();
@@ -162,6 +170,48 @@ public class PrivacySettings extends SettingsPreferenceFragment implements
         }
     };
 
+    private OnPreferenceClickListener preferenceClickListener = new OnPreferenceClickListener() {
+        @Override
+        public boolean onPreferenceClick(Preference preference) {
+			if (preference == mRebootloader) { 
+				RootCommand("reboot loader");
+			}            
+            return false;
+        }	
+	};
+ 

4.2. Android 7.1 实现接口  implements Preference.OnPreferenceClickListener 

--- a/packages/apps/Settings/src/com/android/settings/PrivacySettings.java
+++ b/packages/apps/Settings/src/com/android/settings/PrivacySettings.java
@@ -33,6 +33,7 @@ import android.provider.Settings;
 import android.support.v14.preference.SwitchPreference;
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.Preference.OnPreferenceChangeListener;
+import android.preference.Preference.OnPreferenceClickListener;
 import android.support.v7.preference.PreferenceScreen;
 import android.util.Log;
 
@@ -48,11 +49,14 @@ import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import android.view.View.OnClickListener;
 
 /**
  * Gesture lock pattern settings.
  */
-public class PrivacySettings extends SettingsPreferenceFragment implements Indexable {
+public class PrivacySettings extends SettingsPreferenceFragment implements Preference.OnPreferenceClickListener,Indexable {
 
     // Vendor specific
     private static final String GSETTINGS_PROVIDER = "com.google.settings";
@@ -62,6 +66,7 @@ public class PrivacySettings extends SettingsPreferenceFragment implements Index
     private static final String DATA_MANAGEMENT = "data_management";
     private static final String BACKUP_INACTIVE = "backup_inactive";
     private static final String FACTORY_RESET = "factory_reset";
+	private static final String REBOOT_LOADER_KEY = "reboot_loader_key";
     private static final String TAG = "PrivacySettings";
     private IBackupManager mBackupManager;
     private PreferenceScreen mBackup;
@@ -69,6 +74,7 @@ public class PrivacySettings extends SettingsPreferenceFragment implements Index
     private PreferenceScreen mConfigure;
     private PreferenceScreen mManageData;
     private boolean mEnabled;
+	private Preference mRebootloader;
 
     @Override
     protected int getMetricsCategory() {
@@ -97,6 +103,9 @@ public class PrivacySettings extends SettingsPreferenceFragment implements Index
 
         mConfigure = (PreferenceScreen) screen.findPreference(CONFIGURE_ACCOUNT);
         mManageData = (PreferenceScreen) screen.findPreference(DATA_MANAGEMENT);
+		
+		mRebootloader = (Preference) findPreference(REBOOT_LOADER_KEY);
+		mRebootloader.setOnPreferenceClickListener(this);		
 
         Set<String> keysToRemove = new HashSet<>();
         getNonVisibleKeys(getActivity(), keysToRemove);
@@ -140,7 +149,46 @@ public class PrivacySettings extends SettingsPreferenceFragment implements Index
             return result;
         }
     };
+	
+    @Override
+    public boolean onPreferenceClick(Preference preference) {
+		if (preference == mRebootloader) { 
+			RootCommand("reboot loader");
+		}            
+        return false;
+    }
 

  

  

  

 

  

posted @ 2020-07-20 19:31  CrushGirl  阅读(434)  评论(0编辑  收藏  举报