Asad
Asad

Reputation: 1300

How to add fragment successfully?

I just following a tutorial and don't understand why it's showing error. Here is my codes..

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

    fManager = getFragmentManager();

    MakeTransaction();
}
public void MakeTransaction(){
    MyFragmentClass mfrag = new MyFragmentClass();
    FragmentTransaction trans = fManager.beginTransaction();

    trans.add(R.id.view_group,mfrag,"G");

}

On the line "trans.add(R.id.view_group,mfrag,"G");" I am getting error...

The error is add() in fragment transaction cannot be applied ..

here is the fragment class code##

public class MyFragmentClass extends Fragment {

Button ph;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,        
Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_setup, container,false);

}

here is the main xml code where i have two fragment..

<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">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/view_group"
    android:orientation="horizontal">

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:id="@+id/fragment_setup"
    />

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment_display"
     />
</LinearLayout>
</LinearLayout>

Upvotes: 2

Views: 91

Answers (1)

Blackbelt
Blackbelt

Reputation: 157447

The error is add() in fragment transaction cannot be applied ..

this is usually because of a mismatch between the Fragment imports of your Fragment sublcass and in the Activity. In your case you are using getFragmentManager, and MyFragmentClass is probably a subclass of Fragment from the support library. In your Activity use getSupportFragmentManager() instead of getFragmentManager(). You'll have to extend one between FragmentActivity, AppCompatActivity or ActionBarActivity for this purpose

Upvotes: 3

Related Questions