How do I show a fragment in a card view - Android

2019-09-09 02:45发布

问题:

I want to show a fragment in a card view of android . help required . I have made some fragments already , say one of them is Settings_fragment.xml

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView1"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    card_view:cardUseCompatPadding="true"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:contentPadding="10dp">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/frame">

           //HERE I WANT TO SHOW A FRAGMENT

    </FrameLayout>

</android.support.v7.widget.CardView>

回答1:

Inside a CardView Add a FrameLayout. Then in Activity get that framelayout reference and use addView() method to add that fragment.

Example:

YourFragment fragment = new YourFragment();
Framelayout layout = (FrameLayout) findViewById(R.id.frameLayout);
layout.addView(fragment);


回答2:

a cardview is a framelayout. so just add the fragment directly to the cardview and treat is as a framelayout.