質問

I have a PreferenceActivity where I have a ListPreference with three options. In my MainActivity's xml-file (activity_main.xml) I set the visibility of the Button that is selected in this ListPreference to VISIBLE.

Everything works, except for one small issue. Only after I changed the ListPreference in the settings-screen for the second time, it changes in the main-screen.

To make it more clear:

  1. App is started and MainActivity's activity_main.xml is showed with the last saved Preference button VISIBLE and the other two GONE.
  2. I click on F2 (I work with an Emulator) and click on Settings. The settings menu opens and in the dropdown I select a different option.
  3. When I go back to the activity_main (using Esc as back) nothing has changed.
  4. However, when I open the settings-menu again with F2 and change the setting again, and then go back to the main_layout, the button did change (to the setting I selected in step 2).

So, my question: How do I "refresh" my main_layout after a visibility has changed by a changed preference? (How to show the changes to the activity_main right away when I go back to it.)

Should I add an @Override onResume() method in the MainActivity and call some kind of "refresh" there?

Thanks in advance for the responses.


Here is my code:

MainActivity.java:

public class MainActivity extends ActionBarActivity
{
    ...

    // Public static MainActivity so we can use findViewById from MyPrefsActivity
    public static MainActivity mActivity;

    public static final String LIST_PREFERENCE = "prefCheckboxOption";
    public static String currentValue;

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

        ...

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        currentValue = preferences.getString(LIST_PREFERENCE, "0");

        setChosenPreference(Integer.valueOf(currentValue));

        mActivity = this;
    }

    public void setChosenPreference(int chosen_value){
        // First put all Visibilities on GONE
        cbButton.setVisibility(View.GONE);
        spinnerButton.setVisibility(View.GONE);
        popupButton.setVisibility(View.GONE);

        // Then turn the chosen on VISIBLE again
        switch(chosen_value){
            case 0: // Multi-Click CheckBox
            default:
                cbButton.setVisibility(View.VISIBLE);
                break;
            case 1: // Dropdown CheckBox
                spinnerButton.setVisibility(View.VISIBLE);
                break;
            case 2: // Pop-up CheckBox
                popupButton.setVisibility(View.VISIBLE);
                break;          
        }
    }

    ...

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch(id){
            case R.id.action_settings:
                startActivity(new Intent(this, MyPrefsActivity.class));
                return true;
        }
        return false;
    }
}

MyPrefsActivity.java:

public class MyPrefsActivity extends PreferenceActivity
{
    private static int prefs = R.xml.settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyPreferenceFragment pf = new MyPreferenceFragment();
        getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
    {       
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
            preferences.registerOnSharedPreferenceChangeListener(this);

            MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue));
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            if(key.equals(MainActivity.LIST_PREFERENCE)){
                ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE
                if(listPreference != null){
                    listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                        @Override
                        public boolean onPreferenceChange(Preference preference, Object newValue) {
                            MainActivity.currentValue = (String) newValue;
                            MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue));
                            return false;
                        }
                    });
                }
                else
                    Log.e("MyPrefsActivity", "listPreference is null!");
            }
            else{
                // Other settings
            }
        }
    }
}

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.testproject.MainActivity$PlaceholderFragment" >

    <ImageButton
        android:id="@+id/ibtnCheckbox"
        android:visibility="visible"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:contentDescription="@string/checkbox_content_description"
        android:src="@drawable/checkbox_unchecked"
        android:background="@drawable/transparent_background" />

    <ImageButton
        android:id="@+id/ibtnSpinner"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:contentDescription="@string/checkbox_content_description"
        android:src="@drawable/checkbox_unchecked"
        android:background="@drawable/transparent_background" />

    <ImageButton
        android:id="@+id/ibtnPopup"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:contentDescription="@string/checkbox_content_description"
        android:src="@drawable/checkbox_unchecked"
        android:background="@drawable/transparent_background" />

</LinearLayout>

settings.xml:

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

    <PreferenceCategory android:title="@string/checkbox_options_title" >
        <ListPreference
                android:key="prefCheckboxOption"
                android:title="@string/pref_checkbox_option"
                android:summary="@string/checkbox_options_summary"
                android:entries="@array/checkbox_options"
                android:entryValues="@array/checkbox_option_values" />

    </PreferenceCategory>

</PreferenceScreen>

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="checkbox_options">
        <item>CheckBox as Multi-Click</item>
        <item>CheckBox as Dropdown</item>
        <item>CheckBox as Pop-up</item>
    </string-array>
    <string-array name="checkbox_option_values">
        <item>0</item>
        <item>1</item>
        <item>2</item>
    </string-array>
</resources>

EDIT: As reference to others:

MainActivity.java is exactly the same, except for the added onResume() method as Sir SC posted.

and MyPrefsActivity.java has changed to a much shorter version:

public class MyPrefsActivity extends PreferenceActivity
{
    private static int prefs = R.xml.settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {       
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
            // private members seem to be visible for inner class, and
            // making it static made things so much easier
        }
    }
}
役に立ちましたか?

解決

Create an onResume() function inside your MainActivity.

Set the changes inside your onResume() function, so when you press back from the other Activity, onResume of your MainActivity will be called and the settings you write inside it will be seen.

As I understand from your example it should be like this:

@Override
protected void onResume() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    currentValue = preferences.getString(LIST_PREFERENCE, "0");
    setChosenPreference(Integer.valueOf(currentValue));
    super.onResume();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top