来自PreferenceFragment的AndroidRestart活动

时间:2017-07-17 10:45:31

标签: android android-fragments android-preferences

我在PreferenceFragment之内宣布我的SettingsActivity

public class ChordsSettings extends Activity {

@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(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings_preferences);
    }
}
}

我是这样做的,并没有在MainActivity之上创建片段,因为我需要能够使用后退按钮从SettingsActivityMainActivity这就是实现这一目标的唯一途径。

我需要在首选项更改后重新启动MainActivity

我尝试从Broadcast发送preferenceFragment,但sendBroadcast()无法在静态上下文中使用。还有其他方法可以达到这个目的吗?

1 个答案:

答案 0 :(得分:2)

您的MainActivity应该看起来像这样。请注意,单击btnGoToSetting时会调用finish()方法。这是为了关闭当前的活动。

<强> MainActivity.java

public class MainActivity extends Activity {

    Button btnGoToSetting;

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

        btnGoToSetting = (Button)findViewById(R.id.btnGoToSetting);
        btnGoToSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
            }
        });
    }

}

<强> SettingsActivity.java

public class SettingsActivity extends Activity {

    Button btnSavePreferences;

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

        btnSavePreferences = (Button)findViewById(R.id.btnSavePreferences);
        btnSavePreferences.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Here is where you save all your preferences
                yourSaveFunction();
                finish();
                Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onBackPressed() {
        finish();
        Intent intent = new Intent(SettingsActivity.this, MainActivity.class);
        startActivity(intent);
    }

}

注意:还有另一种方法可以通过使数据异步来重新刷新MainActivity中的数据,这样每次数据更改时它都会自动刷新。