我四处搜寻,但未能找到解决此问题的方法。我有一个正在显示的 fragment ,当您按下按钮时,它会在其之上打开一个新的 Activity 。然后,当该 Activity 完成时,它会将一些 Intent 数据返回给 Fragment/Parent Activity。该数据有时会更改 TextView 或向 Fragment 添加按钮。但是,如果不将 Fragment 重新添加到 backstack(popBackStack 然后替换或添加),我无法更新 Fragment 的 View 。
我尝试过的几件事是在 fragment 的基本布局上调用 invalidate()
和 requestLayout()
但刷新 View 的唯一方法似乎是它通过删除并重新添加它来再次调用 onCreateView()
。有没有办法指定 Fragment 的“内容 View ”而不重新加载它?
家长 Activity 代码:
// Used to retrieve the data from the first Activity
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
// Try to update the Fragment's view here
mMyFragment.refreshView(data.getString(NEW_BUTTON_TEXT));
}
}
fragment 代码(MyFragment):
private View mBaseLayout;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mBaseLayout = inflater.inflate(R.layout.my_layout, container, false);
...
return mBaseLayout;
}
public void refreshView(String newButtonText) {
Button button = mBaseLayout.findViewById(R.id.new_button);
button.setText(newButtonText);
button.setVisibility(View.VISIBLE);
// TODO Reset the Fragment's view with the update mBaseLayout view
// ? ? ?
// Tried mBaseLayout.invalidate() and mBaseLayout.requestLayout() here
}
对此的任何想法都会非常有帮助,谢谢!
最佳答案
由于似乎没有办法强制刷新 Fragment 的 View ,因此我最终只是分离并重新附加该 Fragment,因此再次调用 onCreateView()
。这似乎正是我想要的。我使用此解决方案作为起点,但需要添加 commitAllowingStateLoss()
以防止崩溃:https://stackoverflow.com/a/19409266/1234752 。在这里允许状态丢失是可以的,因为 Fragment 只是被重用并且数据仍然包含在其中。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
myFragment.updateData(data.getString(NEW_BUTTON_TEXT));
// Need to use commitAllowingStateLoss() to prevent an IllegalStateException
// from being thrown
getSupportFragmentManager()
.beginTransaction()
.detach(mContactDetailsFragment)
.attach(mContactDetailsFragment)
.commitAllowingStateLoss();
}
}
关于java - 刷新或重绘 Fragment 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24941787/