I am new to Android development. I have developed a preferences activity in my Android Application. I wanted one Preference to open up a regular Activity. I created a preference object in my XML file and captured the onclick event in order to open the activity.
Code below:
<PreferenceCategory android:title="School">
<Preference
android:key="txtSchoolListPreference"
android:title="Select School"
android:clickable="true" />
</PreferenceCategory>
// Get selected school text box
Preference SelectedSchool =(Preference)findPreference("txtSchoolListPreference");
SelectedSchool.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// Show the login intent
Intent i = new Intent(Settings.this,SchoolList.class);
i.putExtra(One.APP_ACTIVITY_NAME,One.APP_ACTIVITY_SETTINGS);
startActivityForResult(i, One.APP_ACTIVITY_SCHOOLLIST);
return true;
}
});
Everything works great but I would like to add the circle arrow-down icon to the preference but I don't know how.
Does anyone have any idea how I can add the circle arrow-down preference to the preference I have added to the page?
Getting the PreferenceActivity to show like the system's current theme is a bit more involved. Than just showing the Android vanilla arrow. You'll have to create a subclass of DialogPreference (code on github). Use the code from EditTextPreference (code on github) as a template on how to create your subclass. As it appears you'll be starting another Activity this will be easier than creating one that displays another dialog (was not that easy in my experience).
To include your preference in the Preference Resource xml file use the fully qualified name with a leading capital letter. For example class Foo in package com.stackoverflow would appear as <Com.stackoverflow.Foo>. This is similar to how custom view widgets are used in xml layouts.
The reason you have to do it this way is the arrow is an internal resource so we have to go to some extremes to use the internal resource.
Related
I have a settings XML file, implemented in a PreferenceFragmentCompat class. In the XML file, I have a "android.support.v7.preference.EditTextPreference" in a "android.support.v7.preference.PreferenceScreen" like this :
android:key="#string/pref_key_code"
android:maxLines="1"
android:title="#string/pref_code_title"
When it was a simple "EditTextPreference" in a basic PreferenceScreen, this preference was working perfectly, but since I tried to change for v7.preference, it doesn't work anymore and I have this error when I click on it :
java.lang.IllegalStateException: Dialog view must contain an EditText with id #android:id/edit
at android.support.v7.preference.EditTextPreferenceDialogFragmentCompat.onBindDialogView(EditTextPreferenceDialogFragmentCompat.java:67)
at android.support.v7.preference.PreferenceDialogFragmentCompat.onCreateDialog(PreferenceDialogFragmentCompat.java:148)
What do I have to do?
I want to display different preference options in my app depending on the device SDK and screen size, but certain preferences will be displayed on all devices. I could accomplish this by creating a full preferences.xml file for each possible device, like this:
xml/preferences.xml:
<PreferenceScreen>
<!-- Preference 1 (all devices) -->
<!-- Preference 2 (all devices) -->
</PreferenceScreen>
xml-v21/preferences.xml:
<PreferenceScreen>
<!-- Preference 1 (all devices) -->
<!-- Preference 2 (all devices) -->
<!-- Preference 3 (SDK 21 only) -->
</PreferenceScreen>
But this will get unwieldy very quickly given the number of possible combinations of screen sizes and SDKs. What I'd really like to do would be to use the same basic list of preferences on all devices and dynamically mix in additional preferences that are specific to certain screen sizes and SDKs. I've gone through the Android Providing Resources guide, but it seems that using alternative resources in the manner described there would still require me to create a separate resource directory for every screen-size-and-SDK combination and would require a lot of code duplication. Is there a nice, elegant solution to this problem that I'm missing?
Have you read the Settings guide? My app also has a lot of changes dynamically, both in 1) which headers / fragments to show, and 2) which prefs each fragment contains. For both issues you can use different resource versions, as you describe, or you can implement the differences in code.
For issue #1, you can either call loadHeadersFromResource directly, and have different headers resource files, or you can have code that does something similar. For example, my PreferencesActivity uses a separate PreferenceFragment subclass for each prefs section, and makes a decision at run time about which fragments (headers) to show:
#Override
public void onBuildHeaders(List<Header> targets) {
// Build a list of PreferenceFragment class objects to show now
List<Class<? extends PreferenceFragment>> fragmentClasses = ...;
// Create a Header for each fragment to return to Android
for (Class<? extends PreferenceFragment> fragmentClass: fragmentClasses) {
try {
PreferenceFragment fragment = fragmentClass.newInstance();
Header header = new Header();
header.fragment = fragmentClass.getName();
header.titleRes = fragment.getTitleId();
targets.add(header);
this.headers = targets;
} catch (Exception e) {
}
}
}
For issue #2, you can start with preferences from a common resource file, and then add the conditional ones in code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load common prefs from an XML resource
addPreferencesFromResource(R.xml.preferences);
// Add conditional prefs in code
PreferenceScreen prefScreen = getPreferenceScreen();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Preference pref = ...; // create condition pref
prefScreen.addPreference(pref);
}
}
I actually add all prefs in code, common and conditional. However, I didn't see a way to create a PreferenceScreen from scratch, so I actually have an empty XML file that I load from resources, and then add all preferences in code. It works really well.
Hi I want to create preferences in my application but I cannot use resources at all due to some dependency issues.
I am able to do this using the below code:
public class DTMainActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPreferenceScreen(defaultPref());
setDependencies();
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
SwitchPreference dLogTracingEnablePref = new SwitchPreference(this);
dLogTracingEnablePref.setTitle(R_Class.R_String.dLogTracingEnablePrefString);
dLogTracingEnablePref.setDisableDependentsState(false);
dLogTracingEnablePref.setChecked(true);
dLogTracingEnablePref.setKey(R_Class.R_String.dLogTracingEnablePrefKey);
root.addPreference(dLogTracingEnablePref);
}
I would want to do this using the new fragment based approach, without using the deprecated APIs like getPreferenceManager etc.. I can create all the other UI layout elements like linearlayout etc.. without any resources, but when it comes to preferences and PreferenceFragment class, all that is available is addPreferencesFromResource() which would need an XML. Can any one help me here please?
I managed to made it using a PreferenceFragment, without addPreferencesFromResource(),
Instead I just created the PreferenceScreen like you just did and used
try using the bindPreferenceSummaryToValue, consider "p" being a PreferenceScreen with Preferences already added into it, (and also that has been created and configured previously)
PreferenceScreen p = createPreferences();//a method that creates a PreferenceScreen and add some preferences into it
this.setPreferenceScreen(p);
bindPreferenceSummaryToValue(p.findPreference("preference_key"));
I responded to someone with a similar problem here .. perhaps you can check it out
I am tryig to write an Android Honeycomb application and I am having trouble subclassing Preference: http://developer.android.com/reference/android/preference/Preference.html
I want to make a similar layout with title and summary but also a progress bar.
I have created the layout and added the custom preference class but I can't seem to get hold of the instance of it to set the values of the items in it.
It seems that the preference key doesn't work for the custom class.
Here is my preference definition compared to the standard preference class:
<Preference
android:key="int_free_storage"
android:title="Free Space"
android:summary="free storage value here"/>
<com.hamid.storageether.SpacePreference
android:key="int_space_test"
android:title="Test"
android:summary="This is my custom preference"/>
My my preference subclass then sets my XML layout as it's layout resource in its constructor
setLayoutResource(R.layout.space_pref_layout);
it also overrides the setTitle and setSummary methods....
In my main PreferenceActivity I try to get hold of my Preference by it's key but no luck it seems, since the preference never gets updated:
// These Two work
Preference intTotal = (Preference)findPreference("int_total_storage");
Preference intFree = (Preference)findPreference("int_free_storage");
intTotal.setSummary("Standard Preference Summary 1");
intFree.setSummary("Standard Preference Summary 2");
// My subclass doesn't - It just displays the default text defined in the layout xml.
SpacePreference intTest = (SpacePreference)findPreference("int_test_space");
intTest.setTitle("Testtttyyy");
intTest.setSummary("Test Summary");
Could someone please point me towards where I may be going wrong?
Is this code copied straight from the program or retyped? If copied, then your key is "int_space_test" in XML and "int_test_space" in code. It should be throwing a null pointer exception on the next line where you use intTest if that's the case.
I have Listpreferences in my app. They don't appear to be setting to their defaults right after installation - they appear to be null. I'm trying to figure out why my default preferences are not being set right after installation. In my main code I have:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
InUnits = sp.getString("List1", "defValue");
InAngs = sp.getString("List2", "defValue");
OutUnits = sp.getString("List3", "defValue");
OutAngs = sp.getString("List4", "defValue");
Right after the above code executes, each variable contains "defValue" instead of the actual values I have assigned in my ListPreference below.
My preference xml file is called, "settings.xml". Here's what one of the ListPreferences there looks like:
<ListPreference
android:key="List1"
android:title="Input: Alph"
android:summary="Choose Alph or Ralph"
android:entries="#array/inputAlph"
android:entryValues="#array/input_Alph_codes"
android:dialogTitle="Input Alph"
android:defaultValue="ININ"/>
Here's what some of my strings.xml file looks like:
<string-array name="inputUnits">
<item>Alph</item>
<item>Ralph</item>
</string-array>
<string-array name="input_Alph_codes">
<item>ININ</item>
<item>INMM</item>
</string-array>
When I go to menu, and then settings, I can see my defaults checked (radiobuttoned). Then when I go back from the settings menu to my main screen - all is well - for life! ...then each var above is assigned the proper default value.
This only happens when I first install my app on the phone. After I go to the settings screen once and then right out of it, the app is fine and accepts any setting changes.
By the way, as you can see, "List1" is the android:key within a file called settings.xml in my res/xml folder.
They don't appear to be setting to
their defaults right after
installation - they appear to be null.
That's what's supposed to happen.
I'm trying to figure out why my
default preferences are not being set
right after installation.
They're not supposed to be. The preference XML you have listed there is only used for populating a PreferenceActivity, nothing more. Until the user opens the PreferenceActivity, the preferences will be null, and the defaults you supply to the SharedPreferences getters will be returned.
UPDATE
You can use setDefaultValues() on PreferenceManager to assign the defaults from your preference XML to a SharedPreferences. However, be careful of the timing -- this will do disk I/O, and therefore ideally is performed on a background thread.
Set the default values to SharedPreferences from your preference XML.
PreferenceManager.setDefaultValues(Context context, int resourceId, boolean readAgain)
PreferenceManager.setDefaultValues
You can specify a default value like this
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
pref.getString("thePrefKey", "theDefaultValue");
The android:defaultValue="..." in the "layout" settings.xml is only a visual help for user