Android: Adding a fragment to an activity

后端 未结 2 1179
一向
一向 2020-12-16 05:31

I\'m fairly new to Android, so this might have an obvious answer, but I can\'t seem to find it.

I\'m writing a version of a calculator app. I want to make it so tha

相关标签:
2条回答
  • 2020-12-16 05:34

    use easy code in your activity

    getSupportFragmentManager().beginTransaction().add(R.id.yourcontainer,new yourfragment).commit();
    
    0 讨论(0)
  • 2020-12-16 05:41

    The problem here is that the fragment needs a container with a view id to reside within. Giving it a layout id will result in the error you saw.

    You can add the fragment to your relative layout, but to do that properly you'll need to assign it appropriate layout parameters so that it can be placed. It would be easier to just create a FrameLayout within the relative layout that wraps its contents, and then add the fragment there.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <FrameLayout
            android:id="@+id/FragmentContainer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/B1"/>
    
    </RelativeLayout>
    

    Then

    fragmentTransaction.add(R.id.FragmentContainer, fragment);
    
    0 讨论(0)
提交回复
热议问题