简体   繁体   中英

How to go from Activity to Fragment

I know this question has been asked multiple times but I cannot seem to find the answer to my problem.

I have tried the solution of this post: How to go to fragment from activity as shown below:

You need to created a class that extends FragmentActivity and start yourfragment there

public class MessagesFragmentActivity extends SherlockFragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, new MessagesFragment ()).commit();}
    }
}

Your fragment constructor.

public YourFragment() {
}

then from you calling activity, start your fragment activity in the normal way

Intent i = new Intent(YourActivity.this,MessagesFragment.class);
startActivity(i);

But it does not work for me as my activity extends AppCompatActivity, so I cannot extend FragmentActivity.

In this case, I tried creating a new activity which extends FragmentActivity and link an intent to this new activity instead, then this new activity would then move to the fragment.

Below are my codes:

In my Activity:

saveBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listName.getText().toString().equals("")) {
                    listName.requestFocus();
                    listName.setError("Required field");
                } else {
                    if (listOwner.getText().toString().equals("")) {
                        listOwner.requestFocus();
                        listOwner.setError("Required field");
                    } else {
                        params.add(new BasicNameValuePair("userID", userid));
                        params.add(new BasicNameValuePair("Name", listName
                                .getText().toString()));
                        params.add(new BasicNameValuePair("OwnerName",
                                listOwner.getText().toString()));
                        params.add(new BasicNameValuePair("CompanyName",
                                companyName.getText().toString()));
                        params.add(new BasicNameValuePair("CompanyAddress",
                                companyAddress.getText().toString()));
                        params.add(new BasicNameValuePair("CompanyPhone",
                                companyNumber.getText().toString()));

                        for (int d = 0; d < CustomFieldsList.size(); d++) {
                            CustomFields field = CustomFieldsList.get(d);
                            CheckBox cb = (CheckBox) findViewById(field
                                    .getFieldID());
                            if (cb.isChecked()) {
                                checkboxChecked.add(Integer.toString(field
                                        .getFieldID()));
                            }
                        }

                        new SaveContact().execute();
                        Intent back = new Intent(AddContactListActivityOCR.this, Revert.class);
                        startActivity(back);
                        finish();
                    }

In my New Activity (Revert.java):

public class Revert extends FragmentActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, new FragmentContactLists()).commit();}
    }

}

However, it shows the following error in here: 在此处输入图片说明

What went wrong?

-------------------------------------EDIT--------------------------------------

After trying @saeed answer:

It leads to the following: 在此处输入图片说明 在此处输入图片说明

Although I imported "android.support.v4.app.Fragment;", it still shows this error.

Try this: On your Fragment:

 public static MyFragment createFragment() {
        MyFragment fragment = new MyFragment();
        return fragment;
    }

On your activity:

mFragment = MyFragment.createFragment();

       getSupportFragmentManager().beginTransaction().add(
            R.id.fragment_container,
            mFragment).commit();

Try this one. This works for me.

and make sure that you have import V4 fragment. Use replace instead of add.

getSupportFragmentManager().beginTransaction().replace(R.id.fragment_content_id, new SubscriptionFragment(), "")
                      .addToBackStack(null).commit();

you should have a framelayout in your activity xml where you want to use the fragment, id that framelayout to @+id/content ..and replace "android.R.id.content" in your code to R.id.content. That should do the trick.

You Please replace this code

       getSupportFragmentManager().beginTransaction()
  .add(android.R.id.content, new new FragmentContactLists()).commit();

to

getSupportFragmentManager().beginTransaction()
 .replace(R.id.container, new new FragmentContactLists()).commit();

and you replace actyity layout like this

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/container">

</FrameLayout>

In your FragmentContactList you import android.app.Fragment. change it to import android.support.v4.app.Fragment;

Fragment mRideHistory = new fragmentAny();
        getFragmentManager().beginTransaction().replace(R.id.content_frame, mRideHistory)
                .addToBackStack(getPackageName()).commit();

This is a right format for activity to fragment. Use getActivity in any place you need to add this. i hope this information will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM