Frank B.
Frank B.

Reputation: 204

Change fragments in Switch Statement

I have a FragmentAcivity I am using to create a dynamic UI. I want to be able to replace a fragment that only has text with a fragment that may have to post content online, like to Twitter or a server, based on the intent that the FragmentActivity recieves.

I used a switch (like you see below) and Android Studio tells me it cannot resolve the second add() (where I add postFrag) method on my transaction object. What am I missing? If using a switch is a bad idea, how else can it be done?

'fragView` is the fragment container.

private void showContentInContainer() {

    // Get intent to determine next action
    int workType = getIntent().getExtras().getInt(MainActivity.TAG_FRAGWORK);

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();

    // Add the appropriate frag
    switch (workType) {
        case MainActivity.VIEW_RIGHTS :
            // TODO: Pass a rights fragment
            RightsFragment rightsFrag = new RightsFragment();
            transaction.add(R.id.fragView, rightsFrag);
            break;
        case MainActivity.VIEW_SRA :
            // TODO: Pass a view SRA fragment
            PostFragment postFrag = new PostFragment();
            transaction.add(R.id.fragView, postFrag);
            break;
        default: break;
    }
    transaction.commit(); // publish changes
}

EDIT: Added XML of fragment container view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
    <fragment
        android:id="@+id/fragView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</ScrollView>

<fragment
    android:id="@+id/adFragment_2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:name="com.frankbrenyahapps.citisafe.adFragment"
    tools:layout="@layout/fragment_ad"  />
</LinearLayout>

Upvotes: 0

Views: 1189

Answers (1)

Rediska
Rediska

Reputation: 1470

My guess is that postFrag is not actually a subclass of Fragment, or you mixed up android.support.v4.app.Fragment with android.app.Fragment. It has nothing to do with the switch statement.

Upvotes: 1

Related Questions