PreferenceActivity support ActionBarCompat and PreferenceFragment.
Last active
August 29, 2015 14:23
-
-
Save klanjabrik/175bde932c1640dbe200 to your computer and use it in GitHub Desktop.
Implementasi PreferenceActivity (ActionBarCompat, PreferenceFragment)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<!-- 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.sample.myapp.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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<!-- Copyright (C) 2010 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 a primitive example showing the different types of preferences available. --> | |
<PreferenceScreen | |
xmlns:android="http://schemas.android.com/apk/res/android"> | |
<PreferenceCategory | |
android:title="@string/inline_preferences"> | |
<CheckBoxPreference | |
android:key="checkbox_preference" | |
android:title="@string/title_checkbox_preference" | |
android:summary="@string/summary_checkbox_preference" /> | |
<!-- API Level 14 | |
<SwitchPreference | |
android:key="checkbox_preference" | |
android:title="@string/title_switch_preference" | |
android:summary="@string/summary_switch_preference" /> | |
--> | |
</PreferenceCategory> | |
<PreferenceCategory | |
android:title="@string/dialog_based_preferences"> | |
<EditTextPreference | |
android:key="edittext_preference" | |
android:title="@string/title_edittext_preference" | |
android:summary="@string/summary_edittext_preference" | |
android:dialogTitle="@string/dialog_title_edittext_preference" /> | |
<ListPreference | |
android:key="list_preference" | |
android:title="@string/title_list_preference" | |
android:summary="@string/summary_list_preference" | |
android:entries="@array/entries_list_preference" | |
android:entryValues="@array/entryvalues_list_preference" | |
android:dialogTitle="@string/dialog_title_list_preference" /> | |
</PreferenceCategory> | |
<PreferenceCategory | |
android:title="@string/launch_preferences"> | |
<!-- This PreferenceScreen tag sends the user to a new fragment of | |
preferences. If running in a large screen, they can be embedded | |
inside of the overall preferences UI. --> | |
<PreferenceScreen | |
android:fragment="com.sample.myapp.SettingsActivity$Prefs1FragmentInner" | |
android:title="@string/title_fragment_preference" | |
android:summary="@string/summary_fragment_preference"> | |
<!-- Arbitrary key/value pairs can be included for fragment arguments --> | |
<extra android:name="someKey" android:value="somePrefValue" /> | |
</PreferenceScreen> | |
<!-- This PreferenceScreen tag sends the user to a completely different | |
activity, switching out of the current preferences UI. --> | |
<PreferenceScreen | |
android:title="@string/title_intent_preference" | |
android:summary="@string/summary_intent_preference"> | |
<intent android:action="android.intent.action.VIEW" | |
android:data="http://www.android.com" /> | |
</PreferenceScreen> | |
</PreferenceCategory> | |
<PreferenceCategory | |
android:title="@string/preference_attributes"> | |
<CheckBoxPreference | |
android:key="parent_checkbox_preference" | |
android:title="@string/title_parent_preference" | |
android:summary="@string/summary_parent_preference" /> | |
<!-- The visual style of a child is defined by this styled theme attribute. --> | |
<CheckBoxPreference | |
android:key="child_checkbox_preference" | |
android:dependency="parent_checkbox_preference" | |
android:layout="?android:attr/preferenceLayoutChild" | |
android:title="@string/title_child_preference" | |
android:summary="@string/summary_child_preference" /> | |
</PreferenceCategory> | |
</PreferenceScreen> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<!-- Copyright (C) 2010 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 a primitive example showing the different types of preferences available. --> | |
<PreferenceScreen | |
xmlns:android="http://schemas.android.com/apk/res/android"> | |
<CheckBoxPreference | |
android:key="next_screen_checkbox_preference" | |
android:title="@string/title_next_screen_toggle_preference" | |
android:summary="@string/summary_next_screen_toggle_preference" /> | |
</PreferenceScreen> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
... | |
} | |
... | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
switch (item.getItemId()) { | |
... | |
case R.id.action_settings: | |
Intent intentSettings = new Intent(this, SettingsActivity.class); | |
/** | |
* Uncomment below to open specific fragment | |
*/ | |
//intentSettings.putExtra( PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsActivity.Prefs1Fragment.class.getName() ); | |
//intentSettings.putExtra( PreferenceActivity.EXTRA_NO_HEADERS, true ); | |
startActivity(intentSettings); | |
return true; | |
default: | |
return false; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sample.myapp; | |
/* | |
* 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. | |
*/ | |
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]; | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 a primitive example showing how some preferences can depend on other preferences. --> | |
<PreferenceScreen | |
xmlns:android="http://schemas.android.com/apk/res/android"> | |
<PreferenceCategory | |
android:title="@string/example_preference_dependency"> | |
<CheckBoxPreference | |
android:key="wifi" | |
android:title="@string/title_wifi" /> | |
<EditTextPreference | |
android:layout="?android:attr/preferenceLayoutChild" | |
android:title="@string/title_wifi_settings" | |
android:dependency="wifi" /> | |
</PreferenceCategory> | |
</PreferenceScreen> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<preference-headers | |
xmlns:android="http://schemas.android.com/apk/res/android"> | |
<header android:fragment="com.sample.myapp.SettingsActivity$Prefs1Fragment" | |
android:icon="@mipmap/ic_settings_applications" | |
android:title="Prefs 1" | |
android:summary="An example of some preferences." /> | |
<header android:fragment="com.sample.myapp.SettingsActivity$Prefs2Fragment" | |
android:icon="@mipmap/ic_settings_display" | |
android:title="Prefs 2" | |
android:summary="Some other preferences you can see."> | |
<!-- Arbitrary key/value pairs can be included with a header as | |
arguments to its fragment. --> | |
<extra android:name="someKey" android:value="someHeaderValue" /> | |
</header> | |
<header android:icon="@mipmap/ic_settings_display" | |
android:title="Intent" | |
android:summary="Launches an Intent."> | |
<intent android:action="android.intent.action.VIEW" | |
android:data="http://www.android.com" /> | |
</header> | |
</preference-headers> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SettingsActivity extends PreferenceActivity { | |
private AppCompatDelegate mDelegate; | |
private ActionBar bar; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
getDelegate().installViewFactory(); | |
getDelegate().onCreate(savedInstanceState); | |
super.onCreate(savedInstanceState); | |
// Add a button to the header list. | |
if (hasHeaders()) { | |
Button button = new Button(this); | |
button.setText("Some action"); | |
setListFooter(button); | |
} | |
bar = getSupportActionBar(); | |
bar.setDisplayHomeAsUpEnabled(true); | |
bar.setTitle("Settings"); | |
bar.setElevation(0); | |
} | |
public void setActionBarTitle(String title){ | |
getSupportActionBar().setTitle(title); | |
} | |
/** | |
* Populate the activity with the top-level headers. | |
*/ | |
@Override | |
public void onBuildHeaders(List<Header> target) { | |
loadHeadersFromResource(R.xml.preference_headers, target); | |
} | |
/** | |
* This fragment shows the preferences for the first header. | |
*/ | |
public static class Prefs1Fragment extends PreferenceFragment { | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
// Make sure default values are applied. In a real app, you would | |
// want this in a shared function that is used to retrieve the | |
// SharedPreferences wherever they are needed. | |
PreferenceManager.setDefaultValues(getActivity(), | |
R.xml.advanced_preferences, false); | |
// Load the preferences from an XML resource | |
addPreferencesFromResource(R.xml.fragmented_preferences); | |
((SettingsActivity) getActivity()).setActionBarTitle("Prefs1Fragment"); | |
} | |
} | |
/** | |
* This fragment contains a second-level set of preference that you | |
* can get to by tapping an item in the first preferences fragment. | |
*/ | |
public static class Prefs1FragmentInner extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
// Can retrieve arguments from preference XML. | |
Log.i("args", "Arguments: " + getArguments()); | |
// Load the preferences from an XML resource | |
addPreferencesFromResource(R.xml.fragmented_preferences_inner); | |
((SettingsActivity) getActivity()).initSummary(getPreferenceScreen()); | |
((SettingsActivity) getActivity()).setActionBarTitle("Prefs1FragmentInner"); | |
} | |
@Override | |
public void onResume() { | |
super.onResume(); | |
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); | |
} | |
@Override | |
public void onPause() { | |
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); | |
super.onPause(); | |
} | |
@Override | |
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { | |
Preference pref = findPreference(key); | |
((SettingsActivity) getActivity()).updatePrefSummary(pref); | |
} | |
} | |
/** | |
* This fragment shows the preferences for the second header. | |
*/ | |
public static class Prefs2Fragment extends PreferenceFragment { | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
// Can retrieve arguments from headers XML. | |
Log.i("args", "Arguments: " + getArguments()); | |
// Load the preferences from an XML resource | |
addPreferencesFromResource(R.xml.preference_dependencies); | |
((SettingsActivity) getActivity()).setActionBarTitle("Prefs2Fragment"); | |
} | |
} | |
private void initSummary(Preference p) { | |
if (p instanceof PreferenceGroup) { | |
PreferenceGroup pGrp = (PreferenceGroup) p; | |
for (int i = 0; i < pGrp.getPreferenceCount(); i++) { | |
initSummary(pGrp.getPreference(i)); | |
} | |
} else { | |
updatePrefSummary(p); | |
} | |
} | |
private void updatePrefSummary(Preference p) { | |
if (p instanceof ListPreference) { | |
ListPreference listPref = (ListPreference) p; | |
p.setSummary(listPref.getEntry()); | |
} | |
if (p instanceof EditTextPreference) { | |
EditTextPreference editTextPref = (EditTextPreference) p; | |
if (p.getTitle().toString().contains("assword")) | |
{ | |
p.setSummary("******"); | |
} else { | |
p.setSummary(editTextPref.getText()); | |
} | |
} | |
if (p instanceof MultiSelectListPreference) { | |
EditTextPreference editTextPref = (EditTextPreference) p; | |
p.setSummary(editTextPref.getText()); | |
} | |
} | |
@Override | |
public boolean onOptionsItemSelected(MenuItem item) { | |
switch (item.getItemId()) { | |
case android.R.id.home: | |
FragmentManager fm = getFragmentManager(); | |
if (fm.getBackStackEntryCount() > 0) { | |
Log.d("MainActivity", "popping backstack"); | |
fm.popBackStack(); | |
} else { | |
Log.d("MainActivity", "nothing on backstack, calling super"); | |
super.onBackPressed(); | |
} | |
return(true); | |
} | |
return(super.onOptionsItemSelected(item)); | |
} | |
@Override | |
protected void onPostCreate(Bundle savedInstanceState) { | |
super.onPostCreate(savedInstanceState); | |
getDelegate().onPostCreate(savedInstanceState); | |
} | |
public ActionBar getSupportActionBar() { | |
return getDelegate().getSupportActionBar(); | |
} | |
public void setSupportActionBar(@Nullable Toolbar toolbar) { | |
getDelegate().setSupportActionBar(toolbar); | |
} | |
@Override | |
public MenuInflater getMenuInflater() { | |
return getDelegate().getMenuInflater(); | |
} | |
@Override | |
public void setContentView(@LayoutRes int layoutResID) { | |
getDelegate().setContentView(layoutResID); | |
} | |
@Override | |
public void setContentView(View view) { | |
getDelegate().setContentView(view); | |
} | |
@Override | |
public void setContentView(View view, ViewGroup.LayoutParams params) { | |
getDelegate().setContentView(view, params); | |
} | |
@Override | |
public void addContentView(View view, ViewGroup.LayoutParams params) { | |
getDelegate().addContentView(view, params); | |
} | |
@Override | |
protected void onPostResume() { | |
super.onPostResume(); | |
getDelegate().onPostResume(); | |
} | |
@Override | |
protected void onTitleChanged(CharSequence title, int color) { | |
super.onTitleChanged(title, color); | |
getDelegate().setTitle(title); | |
} | |
@Override | |
public void onConfigurationChanged(Configuration newConfig) { | |
super.onConfigurationChanged(newConfig); | |
getDelegate().onConfigurationChanged(newConfig); | |
} | |
@Override | |
protected void onStop() { | |
super.onStop(); | |
getDelegate().onStop(); | |
} | |
@Override | |
protected void onDestroy() { | |
super.onDestroy(); | |
getDelegate().onDestroy(); | |
} | |
public void invalidateOptionsMenu() { | |
getDelegate().invalidateOptionsMenu(); | |
} | |
private AppCompatDelegate getDelegate() { | |
if (mDelegate == null) { | |
mDelegate = AppCompatDelegate.create(this, null); | |
} | |
return mDelegate; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment