我有一个包含视图和选项菜单的片段:
public class OfferingsFragment extends Fragment
{
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.offering_tiles, null);
...
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
在选项菜单中,用户打开此首选项片段,该片段由SettingsActivity:
托管public class SettingsActivity extends Activity {
private SettingsFragment settingsFragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, settingsFragment)
.commit();
}
OfferingsFragment的视图取决于其中一个偏好。也就是说,在此首选项发生更改后,必须通过再次调用onCreateView来刷新OfferingsFragment。我这样做是:
如果我通过主页按钮(ActionBar中的左箭头)返回到OfferingsFragment,则通过调用onCreateView(这是所需的效果)来刷新OfferingsFragment。但是,如果我通过后退按钮(在设备上)返回到OfferingsFragment,则onCreateView不会被调用,因此不会重新创建视图。我想要的是当用户按下后退按钮时也重新创建视图。任何想法如何实现这一目标?
答案 0 :(得分:1)
当您按向上按钮时,通过startActivity
调用父活动,这意味着默认情况下会创建一个新实例。
当您按“返回”按钮时,当前活动已完成,您将返回上一个活动及其已存在的实例(处于停止状态)。
我想要的是当用户按下后退按钮时也会重新创建视图。任何想法如何实现这一目标?
通过startActivityForResult
:
public static final int RC_SETTINGS = 1;
private void startSettingsActivity() {
Intent i = new Intent(this, SettingsActivity.class);
startActivityForResult(i, RC_SETTINGS);
}
当结果返回重新连接片段时。这将重新创建其视图层次结构。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Call to super if you value your life. And want proper lifecycle handling.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SETTINGS) {
// If we just came back from SettingsActivity...
// ...reattach fragment and trigger view recreation.
final FragmentManager fm = getFragmentManager();
final f = fm.findFragmentById(android.R.id.content);
fm.beginTransaction().detach(f).attach(f).commit();
}
}
将片段ID替换为您使用的任何内容。
如果您的片段没有配置错误,您应该可以致电
public class SettingsActivity extends Activity {
private SettingsFragment settingsFragment = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, settingsFragment)
.commit();
} else {
settingsFragment = (SettingsFragment) getFragmentManager().findFragmentById(android.R.id.content);
}
}
}
由于原始代码在配置更改时会失去状态(例如滚动位置),因此这既干练又实用。