0

我想將多個片段添加到LinearLayout。在LinearLayout中以編程方式放置片段

集裝箱代碼

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

    LinearLayout linearLayout = (LinearLayout) rootView.findViewById(R.id.LinLay); 
    linearLayout.addView(MyFragment.newInstance("Params", "Random"),0); 

    return rootView; 
} 

XML集裝箱

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.nt.projet.ToDoList"> 

    <!-- TODO: Update blank fragment layout --> 

    <LinearLayout 
     android:id="@+id/LinLay" 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:animateLayoutChanges="true" 
     android:layout_gravity="center" 
     android:nestedScrollingEnabled="true" 
     android:showDividers="end" 
     android:translationZ="5dp"></LinearLayout> 
</FrameLayout> 

片段代碼

public static MyFragment newInstance(String param1, String param2) { 
     MyFragment fragment = new MyFragment(); 
     Bundle args = new Bundle(); 
     args.putString(ARG_PARAM1, param1); 
     args.putString(ARG_PARAM2, param2); 
     fragment.setArguments(args); 
     return fragment; 
    } 

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

我會dd一些onClickListeners按鈕,我將在Fragment中創建。我想以編程方式將無限數量的片段添加到佈局。我如何去做這件事?

+0

想要創建一個frag的堆棧在LinearLayout中,是嗎? –

+0

@André.C.S是的。這就對了。 – user1

回答

0

您無法添加View(),然後傳遞片段的新實例。這是錯誤的:

linearLayout.addView(MyFragment.newInstance("Params", "Random"),0); 

而在你newInstance(...)改變:

MyFragment fragment = new MyFragment(); 

如果你是在一個活動,而不是FragmentAcitivity你需要使用,然後使用FragmentTransaction

FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
if (mCurrentFragment != null) { 
    mCurrentFragment = NewFragment.newInstance("Your Argument"); 
} 
ft.add(R.id.LinLay, mCurrentFragment,); 
ft.commit(); 

getFragmentManager()而不是getSupportFragmentManager()

相關問題