其他分享
首页 > 其他分享> > android-在视图内部动态添加片段

android-在视图内部动态添加片段

作者:互联网

我已经从这个How do I add a Fragment to an Activity with a programmatically created content view开始

在活动中创建和添加片段.

但是,当我尝试在动态视图中添加相同的片段时,它失败了.

您能解决其背后的问题吗?

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失败而没有显示确切的行号.

解决方法:

您可能会收到这样的消息:

java.lang.ClassCastException: android.view.View cannot be cast to
android.view.ViewGroup

这是因为可以将片段插入ViewGroup或从ViewGroup继承的片段中.您无法将片段插入View.要使您的代码运行,请更改此行:

View view = new View(this);

例如,

FrameLayout view = new FrameLayout(this);//FrameLayout inherits from ViewGroup

标签:android-fragments,android-layout,android
来源: https://codeday.me/bug/20191201/2077426.html