我应该在下面的自定义对话框类中重构代码。
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
public class BaseDialogFragment extends DialogFragment {
public BaseActivity parentActivity;
protected void showMessage(String title, String message) {
MessageDialogFragment dialog = MessageDialogFragment.newInstance(title, message);
dialog.setCancelable(false);
dialog.show(parentActivity.getSupportFragmentManager(), MessageDialogFragment.TAG);
}
//...
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (getChildFragmentManager().getFragments() != null) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
}
}
}
我想转换它:
android.support.v4.app.DialogFragment;
android.support.v4.app.Fragment;
为:
android.app.DialogFragment;
android.app.Fragment;
我无法正确地重写这个:
for (Fragment fragment : getChildFragmentManager().getFragments()) {
if (fragment != null) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
请告诉我该怎么做。
答案 0 :(得分:0)
我找到工作解决方案,但我并不完全确定。我想看看你的意见。
在此处添加列表片段:
private List<WeakReference<Fragment>> fragList = new ArrayList<>();
public List<Fragment> getActiveFragments() {
ArrayList<Fragment> ret = new ArrayList<>();
for (WeakReference<Fragment> ref : fragList) {
Fragment f = ref.get();
if (f != null) {
if (f.isVisible()) {
ret.add(f);
}
}
}
return ret;
}
@Override
public void onAttach(Activity act) {
super.onAttach(act);
if (act instanceof BaseActivity) {
parentActivity = (BaseActivity) act;
fragList.add(new WeakReference(getActiveFragments()));
}
}
我在这里重构:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (getChildFragmentManager().getBackStackEntryCount() > 0) {
for (WeakReference<Fragment> fragmentWeakReference : fragList) {
fragmentWeakReference.get().onActivityResult(requestCode, resultCode, data);
}
}
}