Question

I'm working on developing a Preference screen in Android's base Settings application. To be brief, I'm finding it difficult to access the View objects of the Preferences themselves: I'm looking to set the value of a Switch based on some file input.

I'm loading the Preference screen from the deprecated method:

addPreferencesFromResource(R.xml.preferences);

Right now I'm trying this:

switchOn = (Switch) getActivity().findViewById(getPreferenceManager().findPreference("myPreference").getLayoutResource());

In addition to feeling bad and wrong, it doesn't really seem to work. When I tried evaluating the getLayoutResource() portion, it gave me a string (the documentation says it returns an int), and that string was 'res/layout/preference_holo.xml'.

Thanks for reading.

edit: I'd like to specify/note that the class that contains this code extends PreferenceFragment.

Was it helpful?

Solution

Here is the code Lawrence Angrave from U of Illinois gave us for the Coursera Android App class. I noted in the comments where I added lines or methods to what he gave us. It seems like your having trouble overall, so I gave you a bunch of code to see what works. Maybe you can compare it to your code and see some changes you might want to make.

Just to note, when your getting user input from the Settings activity, you can only get strings. When your getting preferences that you have put in SharedPreferences by code, you have more flexibility such as using floats, ints, etc.

package your.package.name;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ) {
    showPreferencesPreHoneycomb();
}
else {
    showPreferencesFragmentStyle(savedInstanceState); 
}
}

private void showPreferencesFragmentStyle(Bundle savedInstanceState) {
if (savedInstanceState == null) { // if we are going through for the first time
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    Fragment fragment = new MyPreferencesFragment();
    transaction.replace(android.R.id.content, fragment);
    transaction.commit();
}
}

@SuppressWarnings("deprecation")
private void showPreferencesPreHoneycomb() {
    // this file is in res/xml (not layout!)
addPreferencesFromResource(R.xml.penguin_prefs);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class MyPreferencesFragment extends PreferenceFragment
    // I added next two lines
    implements OnSharedPreferenceChangeListener {
private SharedPreferences mPrefs;

public void OnAttach(Activity activity) {
    super.onAttach(activity);
}

    // I added this method
@Override
public void onPause() {
// DONT FORGET TO DO THIS!!!
// If you don't, the old fragments cause Illegal Exceptions!
mPrefs.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

            // this file is in res/xml (not res/layout!)
    this.addPreferencesFromResource(R.xml.penguin_prefs);

            // I added next two lines
    mPrefs = getPreferenceScreen().getSharedPreferences();
    mPrefs.registerOnSharedPreferenceChangeListener(this);

    return super.onCreateView(inflater, container, savedInstanceState);
}
};

// Here is some of my code processing user inputs on the Settings Page
@Override
public void onSharedPreferenceChanged(SharedPreferences p, String key) {
// Here we are validating the user input and...
// updating the "summary" field on the menu to show the new values that
// the user just input or default values if the user entered junk
int pointsToWin;
float paddleHeight;

// Limit points_to_win to 21, with a default of 11
if (key.equals(getResources().getString(R.string.points_to_win_key))) {
try {
    pointsToWin = Integer.parseInt(p.getString(key,
        getResources().getString(R.string.eleven)));
    } catch (Exception ex) {
        // user put in garbage, so fix it.
    pointsToWin = 22;
    }

    if (pointsToWin < 1 || pointsToWin > 21) {
    SharedPreferences.Editor editor = p.edit();
    editor.putString(key,
        getResources().getString(R.string.eleven));
    editor.commit();
    }
   }

// Limit paddle height to > 4% and < 75%
else if (key.equals(getResources().getString(R.string.paddle_height_key))) {
    try {
       paddleHeight = Integer.parseInt(p.getString(key,
                               getResources().getString(R.string.seventeen)));
    } catch (Exception ex) {
    // user put in garbage, so fix it.
    paddleHeight = 100.0f;
}
if (paddleHeight < 4.0f || paddleHeight > 75.0f) {
    SharedPreferences.Editor editor = p.edit();
        editor.putString(key,
        getResources().getString(R.string.seventeen));
    editor.commit();
}
  }

}

Hope this helps!

OTHER TIPS

It still doesn't feel right, but you might want to try with getWidgetLayoutResource() instead of getLayoutResource().

Anyways, if you just want to set the switch value, you can just do

 ((SwitchPreference)getPreferenceManager().findPreference("myPreference")).setChecked(checked)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top