这个例子展示了Activity在没有进去preferncesActivity 通过PreferenceManager获取preferncesActivity的默认值和shareprefercne的监听,以及自定的Prefernces
LaunchingPreferences展示通过PreferenceManager获取preferncesActivity的默认值
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
/**
* Demonstrates launching a PreferenceActivity and grabbing a value it saved.
*/
public class LaunchingPreferences extends Activity implements OnClickListener {
private static final int REQUEST_CODE_PREFERENCES = 1;
private TextView mCounterText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* If this were my app's main activity, I would load the default values
* so they're set even if the user does not go into the preferences
* screen. Another good place to call this method would be from a
* subclass of Application, so your default values would be loaded
* regardless of entry into your application (for example, a service or
* activity).
*/
PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
// Simple layout
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
// Create a simple button that will launch the preferences
Button launchPreferences = new Button(this);
launchPreferences.setText(getString(R.string.launch_preference_activity));
launchPreferences.setOnClickListener(this);
layout.addView(launchPreferences, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mCounterText = new TextView(this);
layout.addView(mCounterText, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
updateCounterText();
}
public void onClick(View v) {
// When the button is clicked, launch an activity through this intent
Intent launchPreferencesIntent = new Intent().setClass(this, AdvancedPreferences.class);
// Make it a subactivity so we know when it returns
startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// The preferences returned if the request code is what we had given
// earlier in startSubActivity
if (requestCode == REQUEST_CODE_PREFERENCES) {
// Read a sample value they have set
updateCounterText();
}
}
private void updateCounterText() {
// Since we're in the same package, we can use this context to get
// the default shared preferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
final int counter = sharedPref.getInt(AdvancedPreferences.KEY_MY_PREFERENCE, 0);
mCounterText.setText(getString(R.string.counter_value_is) + " " + counter);
}
}
AdvancedPreferences shareprefercne的监听
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import com.example.android.apis.R.color;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceActivity;
import android.preference.CheckBoxPreference;
import android.widget.Toast;
/**
* Example that shows finding a preference from the hierarchy and a custom preference type.
*/
public class AdvancedPreferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_MY_PREFERENCE = "my_preference";
public static final String KEY_ADVANCED_CHECKBOX_PREFERENCE = "advanced_checkbox_preference";
private CheckBoxPreference mCheckBoxPreference;
private Handler mHandler = new Handler();
/**
* This is a simple example of controlling a preference from code.
*/
private Runnable mForceCheckBoxRunnable = new Runnable() {
public void run() {
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}
// Force toggle again in a second
mHandler.postDelayed(this, 1000);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the XML preferences file
addPreferencesFromResource(R.xml.advanced_preferences);
// Get a reference to the checkbox preference
mCheckBoxPreference = (CheckBoxPreference)getPreferenceScreen().findPreference(
KEY_ADVANCED_CHECKBOX_PREFERENCE);
}
@Override
protected void onResume() {
super.onResume();
// Start the force toggle
mForceCheckBoxRunnable.run();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
mHandler.removeCallbacks(mForceCheckBoxRunnable);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Let's do something when my counter preference value changes
if (key.equals(KEY_MY_PREFERENCE)) {
Toast.makeText(this, "Thanks! You increased my count to "
+ sharedPreferences.getInt(key, 0), Toast.LENGTH_SHORT).show();
}
}
}
advanced_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2008 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- This is an advanced example showing the custom preference types and manually handling
preference clicks. -->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<!-- My custom preference type. This just replaces the actual widget
portion of the preference, if the whole preference wanted to be
replaced we would use the layout attribute instead of the widgetLayout
attribute. -->
<com.example.android.apis.app.MyPreference
android:key="my_preference"
android:title="@string/title_my_preference"
android:summary="@string/summary_my_preference"
android:defaultValue="100" />
<CheckBoxPreference
android:key="advanced_checkbox_preference"
android:title="@string/title_advanced_toggle_preference"
android:summaryOn="@string/summary_on_advanced_toggle_preference"
android:summaryOff="@string/summary_off_advanced_toggle_preference" />
</PreferenceScreen>
MyPreference展示了自定义Preference
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
import com.example.android.apis.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
/**
* This is an example of a custom preference type. The preference counts the
* number of clicks it has received and stores/retrieves it from the storage.
*/
public class MyPreference extends Preference {
private int mClickCounter;
// This is the constructor called by the inflater
public MyPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setWidgetLayoutResource(R.layout.preference_widget_mypreference);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
// Set our custom views inside the layout
final TextView myTextView = (TextView) view.findViewById(R.id.mypreference_widget);
if (myTextView != null) {
myTextView.setText(String.valueOf(mClickCounter));
}
}
@Override
protected void onClick() {
int newValue = mClickCounter + 1;
// Give the client a chance to ignore this change if they deem it
// invalid
if (!callChangeListener(newValue)) {
// They don't want the value to be set
return;
}
// Increment counter
mClickCounter = newValue;
// Save to persistent storage (this method will make sure this
// preference should be persistent, along with other useful checks)
persistInt(mClickCounter);
// Data has changed, notify so UI can be refreshed!
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// This preference type's value type is Integer, so we read the default
// value from the attributes as an Integer.
return a.getInteger(index, 0);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
// Restore state
mClickCounter = getPersistedInt(mClickCounter);
} else {
// Set state
int value = (Integer) defaultValue;
mClickCounter = value;
persistInt(value);
}
}
@Override
protected Parcelable onSaveInstanceState() {
/*
* Suppose a client uses this preference type without persisting. We
* must save the instance state so it is able to, for example, survive
* orientation changes.
*/
final Parcelable superState = super.onSaveInstanceState();
if (isPersistent()) {
// No need to save instance state since it's persistent
return superState;
}
// Save the instance state
final SavedState myState = new SavedState(superState);
myState.clickCounter = mClickCounter;
return myState;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (!state.getClass().equals(SavedState.class)) {
// Didn't save state for us in onSaveInstanceState
super.onRestoreInstanceState(state);
return;
}
// Restore the instance state
SavedState myState = (SavedState) state;
super.onRestoreInstanceState(myState.getSuperState());
mClickCounter = myState.clickCounter;
notifyChanged();
}
/**
* SavedState, a subclass of {@link BaseSavedState}, will store the state
* of MyPreference, a subclass of Preference.
* <p>
* It is important to always call through to super methods.
*/
private static class SavedState extends BaseSavedState {
int clickCounter;
public SavedState(Parcel source) {
super(source);
// Restore the click counter
clickCounter = source.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
// Save the click counter
dest.writeInt(clickCounter);
}
public SavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
preference_widget_mypreference
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Custom preference type using a text view. -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mypreference_widget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="6sp"
android:focusable="false"
android:clickable="false" />