在索引处将CustomFragment添加到Layout

时间:2017-05-09 14:45:54

标签: android android-fragments

方案

我有一个LinearLayout,并希望动态添加CustomFragments(所有相同的类)。 我将所述片段存储在ArrayList(fragSteps)中以便更轻松地处理它们。 由于我需要枚举,添加和删除它们,我希望将它们全部保存在LinearLayout中,因此我不需要处理任何开销。

我正在寻找的是片段相当于Layout.addView(View, Index)或者是一种在片段附加到布局后轻松移动片段位置的方法。

代码

要添加和删除片段,我只使用以下两行:

public void addFragment(int index)
{
    getFragmentManager().beginTransaction().add
            (R.id.layout, fragSteps.get(index + 1)).commit();
}

public void removeFragment(int index)
{
    getFragmentManager().beginTransaction().remove(fragSteps.get(index)).commit();
}

如果需要,请在评论中说明。

1 个答案:

答案 0 :(得分:0)

作为sollution尝试使用视图中的每个片段,以便您可以使用视图来控制

public View addFrag(FragmentSecondParent fragment)
    {
        View view=new View(getActivity());
        FragmentManager fragmentManager=getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.add(view.getId(),fragment).commit();
        return view;
    }
    public void removeFrag(View view)
    {
        view.setVisibility(View.GONE);
    }
    
//to use the above Methods
{
List<View> views=new ArrayList();
        LinearLayout layout=findViewById(...);
        //add these view to a List to get them just by the index
        View view=addFrag(new FragmentSecondParent());
        views.add(view);
        layout.add(view);
        }