如何让android主要活动重新加载'从外面?

时间:2015-12-06 16:49:04

标签: android android-activity

我有一个android主要活动,显示从数据库中获取的一些数据。现在,当用户想要更改某些首选项或删除数据库的内容时,会显示PreferenceActivity。但如果是这种情况,我该如何强行重新加载?或主要活动之外的一个主要活动?

2 个答案:

答案 0 :(得分:1)

OnSharedPreferenceChangeListener中设置MainActivity监听器,以自动检测偏好设置中的任何更改。

SharedPreferencesListener

MainActivity.java

public class MainActivity extends ... {

    private SharedPreferences settings;
    private SharedPreferences.OnSharedPreferenceChangeListener listener;
    ...

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

        settings = PreferenceManager.getDefaultSharedPreferences(this);
        listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                // Refresh display
                refreshDisplay();
            }
        };

        // Register the listener on the SharedPreferences
        settings.registerOnSharedPreferenceChangeListener(listener);

        // Other code
    }

    public void refreshDisplay() {
        // Retrieve entries from sharedPreferences & display them, e.g
        String prefValue1 = settings.getString("key1", "default value 1");
        String prefValue2 = settings.getString("key2", "default value 2");

        // Update UI with these values
    }
}

编辑:

以下是PreferenceActivity应该如何:

public class SettingsActivity extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // R.xml.settings refers to the XML layout file named "settings"
        // in your res/xml directory
        addPreferencesFromResource(R.xml.settings);
    }
}

答案 1 :(得分:-1)

如果您只想为活动充值,可以执行以下操作:

    finish();
    startActivity(getIntent());