java.lang.IllegalArgumentException: No view found

2019-01-18 08:38发布

问题:

I am trying to move from one fragment to another.. It shows following error during fragment transaction-

    java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)

Below are the classes.I have used following code for fragment transaction

Fragment fragment = new PhotosFragment2();

                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.replace(android.R.id.content, fragment);
                        fragmentTransaction.commit();

PhotosFragment.java

   public class PhotosFragment extends Fragment {
        private FragmentActivity myContext;
        @Override
        public void onAttach(Activity activity) {
            myContext = (FragmentActivity) activity;
            super.onAttach(activity);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.photos, container, false);

            rootView.setVerticalScrollBarEnabled(false);
            int[] mThumbIds = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4, R.drawable.album8,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album12, R.drawable.album10,
            };

            int[] mThumbIds2 = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
            };

            CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
            GridView grid = (GridView)rootView.findViewById(R.id.gridView);
            final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
            grid.setFocusable(false);

            grid.setAdapter(adapter);
    grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment = new PhotosFragment2();

            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(android.R.id.content, fragment);
            fragmentTransaction.commit();
        }
    });
            CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
            GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
            grid2.setFocusable(false);
            grid2.setAdapter(adapter2);
            grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Fragment fragment = new PhotosFragment2();

                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(android.R.id.content, fragment);
                    fragmentTransaction.commit();
                }
            });

            return rootView;
        }


    }

PhotosFragment2.java

public class PhotosFragment2 extends Fragment {
    private FragmentActivity myContext;
    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.photos2, container, false);
        myContext.getActionBar().hide();
        return rootView;
    }
}

Activity xml file

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/left_drawer_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bgmenu"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/profilelayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:paddingTop="10dp">


            <ImageView
                android:id="@+id/drawer_profile_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_alignLeft="@+id/drawer_profile_background"
                android:layout_alignRight="@+id/drawer_profile_background"
                android:layout_alignTop="@+id/drawer_profile_background"
                android:layout_marginBottom="7.667dp"
                android:layout_marginLeft="6.5dp"
                android:layout_marginRight="8.3dp"
                android:layout_marginTop="7.667dp"
                android:scaleType="centerCrop"></ImageView>


            <ImageView
                android:id="@+id/drawer_profile_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:src="@drawable/profileblock">

            </ImageView>

            <ImageView
                android:id="@+id/settingicon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_marginLeft="-15dp"
                android:layout_toRightOf="@+id/drawer_profile_background"
                android:background="@drawable/settings" />

            <textview
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/drawer_profile_background"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceListItemSmall"
                android:textColor="@android:color/white" />


        </RelativeLayout>


        <ListView
            android:id="@+id/list_slidermenu"
            style="@style/buttonStyle"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="30dp"
            android:layout_weight="2"
            android:cacheColorHint="@android:color/transparent"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="1dp"
            android:listSelector="@android:color/transparent"
            android:scrollbars="none" />

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

回答1:

When you use fragmentTransaction.replace(R.id.container,fragment) it will remove any fragments that are already in the container and add your new one to the same container.

Now i can suggest you 2 things.First, if you want to use fragmentTransaction.replace(android.R.id.content, fragment); which you are doing right now,then don't set content for your Activity using setContentView.This should work fine then.To know what exactly android.R.id.content is you can refer this stackoverflow question and answer

Or Secondly, In the layout of your Activity have a FrameLayout whose id is content. And then use

fragmentTransaction.replace(R.id.content, fragment);  
fragmentTransaction.addToBackStack(null);//add the transaction to the back stack so the user can navigate back
// Commit the transaction
fragmentTransaction.commit();  

Hope this helps.

More Info:

From your comments it seems that you are having some problem in getting the idea of using FrameLayout in your Activity's layout(Not of any of the Fragment's layout).From the Documents

FrameLayout is designed to block out an area on the screen to display a single item. Generally, FrameLayout should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other.

So the main purpose of FrameLayout is to block the area required to fit the largest child view. If you use a FrameLayout as Fragment Container you can ensure that you always have the space available to accommodate the largest Fragment's layout.

So you can have your FrameLayout something like this in your Activity's layout xml file

<FrameLayout
    android:id="@+id/content"
    android:layout_height="match_parent"
    android:layout_width="match_parent">
 <!--you can put your existing views of your current xml here, so yes your entire xml is now inside this FrameLayout -->
</FrameLayout>


回答2:

I don't use getSupportFragmentManager(). I use getChildFragmentManager() and it worked for me. You can try it.



回答3:

If you are trying to put Fragment into Fragment, use getChildFragmentManager()



回答4:

If you are using ViewPager, use getChildFragmentManager() for pager adapter

viewPager.setAdapter(new ItemsAdapter(getChildFragmentManager()));


回答5:

You have to set a content view in your Activity that your PhotosFragment is attached.

protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.activity_main);

    //...
}


回答6:

There are 2 most common reasons for this problem

  1. Specifying the wrong layout in setContentView() of the onCreate() method
  2. Error also occurs when having nested Fragments and adding them with getSupportFragmentManager() instead of getChildFragmentManager()

Hope this will help

Summved



回答7:

i know this is very late. But it may work for other's.

I declared the id for each layout, like (3rd line bellow)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"


回答8:

Since Android 4.2 (API 17) nested fragments become avaliable. See this

To place fragment inside other fragment use getChildFragmentManager()

Also available in support library.



回答9:

Put this block of code in PhotosFragment2 onCreateView method:

View rootView = inflater.inflate(R.layout.photos2, null);

instead of:

View rootView = inflater.inflate(R.layout.photos2, container, false);


回答10:

in my case I had to change

ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
                container);

to

ViewGroup root = (ViewGroup) inflater.inflate(R.layout.sample,
                container, false);


回答11:

This answer highlights a silly mistake that may occur, that arises when nesting fragments or you are converting activities to fragments.

If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.

In BaseFragment.java OnCreateView:

if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.container, new DifferentFragment())
                    .commit();
        }

return super.onCreateView(inflater, container, savedInstanceState);

Replace super.onCreateView(inflater, container, savedInstanceState); with inflating the correct layout for the fragment:

        return inflater.inflate(R.layout.base_fragment, container, false);


回答12:

The problem may be that you add a fragment and beginTransaction in some fragment like

getFragmentManager().beginTransaction().replace(android.R.id.content, ImageBrowseFragment.newInstance(bundle),"ImageBrowseFragment")
            .addToBackStack(null).commit();

I just change getFragmentManager() to getActivity().getSupportFragmentManager()

Then everything goes fine

When you add a fragment in a fragment use android.R.id.content Or Window.ID_ANDROID_CONTENT,I guess it represents the root container of your fragment not the activity. So change to getActivity().getSupportFragmentManager() works it out



回答13:

I had the same error and after trying a lot of things I found that the problem was with the "id" and "getActivity().getSupportFragmentManager()".

Before i implement i like these

txt_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    getChildFragmentManager()
                            .beginTransaction()
                            .replace(R.id.content_frame, new OpportunitiesFragment())
                            .commit();                }

            });

Then i changed to these

 txt_more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
    ## Heading ##
                        getActivity().getSupportFragmentManager()
                                .beginTransaction()
                                .replace(android.R.id.content, new OpportunitiesFragment())
                                .commit();                }
                });