所以为了让事情变得简单,我的应用程序由一堆卡片组成(谷歌风格)。在设置中,用户可以选择在主活动中可以查看的卡。我的问题是,我不知道如何在用户选择启用哪些卡后更新主活动。
希望这张图能解释我想说的。
main activity --> (menu button) --> settings (menu item) --> preference fragment (settings screen) --> (user selects which cards are enabled) --> (back button) --> (main activity should reflect the changes)
我研究过使用onResume方法,然后在其中调用recreate()。不确定我是否朝着正确的方向前进。我添加后应用程序崩溃。
主要活动.java
public void onCreate(Bundle savedInstanceState) {
//remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// init CardView
mCardView = (CardUI) findViewById(R.id.cardsview);
mCardView.setSwipeable(true);
CardStack freqUsedGroup = new CardStack();
freqUsedGroup.setTitle("Easy Access Cards");
mCardView.addStack(freqUsedGroup);
loadPref();
//Begin UMass Website Card
MyPlayCard umassEduCard = new MyPlayCard("UMass.edu",
"Click this card to access UMass Amherst Website", "#881c1c",
"#CC0000", true, true);
umassEduCard.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.umass.edu/"));
startActivity(intent);
}
});
//end UMass Website Card
if(my_checkbox_preference == true)
{
mCardView.addCard(umassEduCard);
}
mCardView.refresh();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SetPreferenceActivity.class);
startActivityForResult(intent, 0);
return true;
}
private void loadPref() {
SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
my_checkbox_preference = mySharedPreferences.getBoolean("umass_website", false);
}
设置碎片.java
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.layout.preferences);
}
}
谢谢,如果还需要xml等代码,请告诉我。
您应该使用startActivityForResult机制。
这里有一些伪代码:
MainActivity -> startActivityForResult(Settings activity)
settingActivity.onCreate() -> setResult(RESULT_CANCELED)
if any settings is actually changed -> setResult(RESULT_OK)
mainActivity.onActivityResult -> if( RESULT_OK )
// you can try to actually change stuff or, make it a pretty simpler.
// just re-start the whole thing
startActivity(new Intent(this, this.class));
finish();
编辑:
从片段中,您可以调用类似于的setResult
方法
// inside SettingsFragment
// whenever something changed in the settings and you want to re-start the MainAcitivty
getActivity().setResult(RESULT_OK);
// simple!
仍然是MainActivity和SetPreferenceActivity在进行"活动结果"通信,由SettingsFragment负责;)