1

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

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

为此,我有:

主.java

public class Main extends FragmentActivity {

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

主要的.xml

<RelativeLayout     

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

    <Button
        ... />
    ...

</LinearLayout>

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

这是在容器框架布局上动态设置的活动/框架的示例:

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);

所以,问题是如何将框架布局定义为 content1 活动/框架的容器,以及如何设置它?(记住当我触摸按钮时我调用了活动/片段)

4

2 回答 2

3

点击按钮

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

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

于 2013-11-05T12:19:40.360 回答
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
于 2013-11-05T12:21:32.750 回答