我是Fragments的新手。我试过简单的片段示例。但它会引发错误。我不知道出了什么问题。
public class NewActivity extends Activity {
int mStackLevel = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
public static class NewFragment extends Fragment {
int mNum;
Context context;
static NewFragment newInstance(int num) {
NewFragment f = new NewFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
context = getActivity();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.example_fragment, container,
false);
return v;
}
}
}
我的logcat显示:
java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.FragmentExample / com.example.FragmentExample.NewActivity}:java.lang.IllegalArgumentException:找不到片段NewFragment {40ff0850#0 id的id 0x7f07003c的视图= 0x7f07003c}
答案 0 :(得分:6)
ft.add(R.id.simple_fragment, newFragment).commit();
您错过了setContentView
您的活动。如果没有View层次结构,则无法添加片段。
注意:您的片段由活动托管。因此,您需要先将内容设置为活动。
答案 1 :(得分:1)
只需用您的方法替换此方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(Your_layout_file);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
你错过了这一行setContentView(Your_layout_file);
答案 2 :(得分:0)
这个答案强调了可能发生的一个愚蠢的错误,即在嵌套片段或将活动转换为片段时出现的错误。
如果您尝试使用fragmentManager
替换片段中的片段,但不会使父片段膨胀,则可能会导致问题。
在 BaseFragment.java OnCreateView
中:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
替换super.onCreateView(inflater, container, savedInstanceState);
为片段充气正确的布局:
return inflater.inflate(R.layout.base_fragment, container, false);