动态设置片段

时间:2013-11-05 12:12:44

标签: java android layout android-fragments

我有一个FragmentActivty,它的布局由一个LinearLayout组成,左半边有一些按钮,而半边右边是一个空容器FrameLayout,我想插入其他活动(也许它们应该是片段而不是活动)。

根据我触摸的按钮,它将调用一个活动/片段,这将显示在容器framelayout上。

为此,我有:

Main.java

public class Main extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

main.xml中

<RelativeLayout     

<!-- Buttons containing layout -->    
<LinearLayout 

    <Button
        ... />
    ...

</LinearLayout>

<!-- Blank space which will contain other activities -->
<FrameLayout
    android:id="@+id/activitycontent"
    ...>    
</FrameLayout>   

这是在容器framelayout上设置dinamically的活动/框架的示例:

Content1.java

public class Content1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /**Inflate the layout for this fragment*/
    return inflater.inflate(R.layout.content1, container, false);
}

@Override
public void onActivityCreated(Bundle state) {
    super.onActivityCreated(state);

所以,问题是如何将framelayout定义为content1 activity / frament的容器,以及我如何设置它? (记住我在触摸按钮时调用了activty / fragment)

2 个答案:

答案 0 :(得分:3)

点击按钮

Content1 fragment = new Content1();
FragmentManager fragmentManager = getSupportFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.activitycontent, fragment);
fragmentTransaction.commit();

以编程方式将片段添加到现有ViewGroup(容器)。 在活动运行的任何时候,您都可以将片段添加到活动布局中。您只需指定放置片段的ViewGroup

答案 1 :(得分:0)

要加载片段,请执行

public void switchContent(Fragment fragment, boolean addToBackStack)
{
    FragmentManager fragmentManager = getSupportFragmentManager();
    if(fragmentManager == null)
    {
        Log.e("switchContent", "Fragment manager is null, exiting");
        return;
    }
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    if(fragmentTransaction == null)
    {
        Log.e("switchContent", "Fragment transaction is null, exiting");
        return;
    }

    fragmentTransaction.replace(R.id.activitycontent, fragment);
    if(addToBackStack)
    {
        fragmentTransaction.addToBackStack(null);
    }

    fragmentTransaction.commit();
}

单击该按钮将此方法调用为

switchContent(new Content1(), false); 

switchContent(new Content1(), true); // if want this fragment to be added in stack