首页 > 解决方案 > android - 在片段中创建布局并设置新 ID

问题描述

我试图以编程方式创建一个新的布局,我需要在该视图中放入一个新的片段。因此,当我创建该布局(即包含片段的布局)时,我必须设置一个 ID 以在片段事务的 .replace 方法中引用。我用谷歌搜索,我发现有一种方法可以生成一个 id 但它不起作用。它返回数字 1,然后是数字 2,等等。然后我的视图没有被找到。任何想法?忽略 FOR 直到 < 1,它只是为了测试。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_video_holder, container, false);


        FragmentManager fragmentManager = getFragmentManager();
        //FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        mainVideoContainer = view.findViewById(R.id.main_video_container);
        containerLayout = view.findViewById(R.id.videoFragmentContainer);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) containerLayout.getLayoutParams();

        for (int i = 0; i < 1 ; i++) {
            LinearLayout newLinear = new LinearLayout(getContext());
            newLinear.setLayoutParams(params);
            newLinear.setOrientation(LinearLayout.VERTICAL);
            int idGen = View.generateViewId();
            newLinear.setId(idGen);
            testFragment testFragment = new testFragment();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(idGen,testFragment);
            fragmentTransaction.commit();
            mainVideoContainer.addView(newLinear);
        }




        videos = new ArrayList<>();

        return view;
    }

标签: androidlayout

解决方案


我只是通过更改它来修复它:

int idGen = View.generateViewId() + 878977;

我确定这是完全错误的,但它有效。


推荐阅读