我已经开始了如何使用以编程方式创建的内容视图将片段添加到活动中
在 Activity 中创建和添加 Fragment。
但是当我尝试在动态视图中添加相同的片段时,它失败了。
你能解决它背后的问题吗?
public class MainActivity extends FragmentActivity {
private static final int CONTENT_VIEW_ID = 10101010;
private static final int CONTENT_VIEW_ID1 = 10101011;
public FragmentManager fm = getSupportFragmentManager();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = new View(this);
FrameLayout frame = new FrameLayout(this);
frame.setId(CONTENT_VIEW_ID);
frame.addView(view,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.setId(CONTENT_VIEW_ID1);
setContentView(frame);
if (savedInstanceState == null) {
Fragment newFragment1 = new DebugExampleTwoFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(CONTENT_VIEW_ID1, newFragment1);
ft.commit();
}
public static class DebugExampleTwoFragment extends Fragment {
public static int count = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = new View(getActivity());
v.setBackgroundColor(Color.RED);
return v;
}
}
它失败了ClassCastException
,没有显示确切的行号。