【发布时间】:2016-06-25 18:09:51
【问题描述】:
过去几个小时我一直在尝试搜索 SO,但除了尝试创建解决方法之外我找不到解决方案。我正在尝试为我的应用程序创建一个导航抽屉,但为此我不得不最终尝试将我的基本活动更改为一个片段。结果如下:
public class ToolReaderActivity extends Fragment implements ToolListFragment.OnToolSelectedListener, CompatActionBarNavListener, OnClickListener {
boolean mIsDualPane = false;
Context c;
ToolListFragment mToolListFragment;
InfoFragment mInfoFragment;
Fragment mContent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.onepane_with_bar, container, false);
// find our fragments
mToolListFragment = (ToolListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolList);
mInfoFragment = (InfoFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolInfo);
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolList, mToolListFragment).commit();
FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.toolInfo, mInfoFragment).commit();
mToolListFragment.setContext(c);
mToolListFragment.setOnToolSelectedListener(this);
View infoView = getView().findViewById(R.id.toolInfo);
mIsDualPane = infoView != null && infoView.getVisibility() == View.VISIBLE;
int catIndex = savedInstanceState == null ? 0 : savedInstanceState.getInt("catIndex", 0);
setUpActionBar(mIsDualPane, catIndex);
mToolListFragment.setSelectable(mIsDualPane);
restoreSelection(savedInstanceState);
if (savedInstanceState != null) {
//Restore the fragment's instance
mContent = getActivity().getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
}
return rootView;
}
...
...
...
}
预期的输出是一个带有导航抽屉的活动,因此是一个片段。片段包含这个主要活动 ToolReaderActivity(之所以这样命名,是因为它以前是一个活动),其中有 1-2 个片段。它是一个 ListFragment,带有一个显示所选项目信息的片段(如果 mDualPane 为 true,则作为另一个片段,否则作为单独的活动启动)。
我想不出办法让它工作,我已经厌倦了改变使用 onCreate、onCreateView、onActivityCreated 完成的顺序,但我不断收到的错误是 mToolsListFragment 在 mToolsListFragment.setContext 处为空(c);
【问题讨论】:
-
将此行
mToolListFragment = (ToolListFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.toolList);移到transaction.replace(...)下方
标签: java android android-fragments