Fragment 和 FragmentStatePagerAdapter 中带有 ViewPager 的片段导致异常(带有完整示例)

Posted

技术标签:

【中文标题】Fragment 和 FragmentStatePagerAdapter 中带有 ViewPager 的片段导致异常(带有完整示例)【英文标题】:Fragment with ViewPager inside Fragment and FragmentStatePagerAdapter results in Exception (with complete example) 【发布时间】:2013-09-13 10:56:47 【问题描述】:

我有一个带有 ViewPager 的简单片段。

我正在使用最新的支持库 v4 rev18!

如果我第一次显示子片段,一切正常,如果我返回并再次显示,应用程序崩溃并出现以下异常:

我有一个完整的例子显示,当发生以下异常时:

java.lang.NullPointerException
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:569)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1281)
at android.view.View.dispatchRestoreInstanceState(View.java:12043)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2688)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2694)
at android.view.View.restoreHierarchyState(View.java:12021)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:425)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:949)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4800)
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:798)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
at dalvik.system.NativeStart.main(Native Method)

我能够以其他方式在子片段中使用 ViewPager,但如果我手动添加/删除子片段并在子片段中使用 FragmentStatePagerAdapter,我将无法使其正常工作...

下面的例子应该可以工作,但它没有......我已经添加了一些解决一些问题的代码,但它并不能解决所有问题......

import java.lang.reflect.Field;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class TestActivity extends FragmentActivity implements OnClickListener

    private Fragment fragment1;
    private Fragment fragment2;

    public void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_main);

        fragment1 = getSupportFragmentManager().findFragmentByTag("fragment1");
        fragment2 = getSupportFragmentManager().findFragmentByTag("fragment2");
    

    @Override
    public void onClick(View v)
    
        Fragment nextFragment = null;
        String nextFragmentTag = null;
        if (v.getId() == R.id.button1)
        
            if (fragment1 == null)
                fragment1 = ContainerFragment.newInstance(1);
            nextFragment = fragment1;
            nextFragmentTag = "fragment1";
        
        else if (v.getId() == R.id.button2)
        
            if (fragment2 == null)
                fragment2 = ContainerFragment.newInstance(2);
            nextFragment = fragment2;
            nextFragmentTag = "fragment2";
        

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.main, nextFragment, nextFragmentTag);
        transaction.addToBackStack(null);
        transaction.commit();
    

    public static class MainPagerAdapter extends FragmentStatePagerAdapter
    
        public int button;

        public MainPagerAdapter(FragmentManager fm)
        
            super(fm);
        

        @Override
        public Fragment getItem(int i)
        
            return SubFragment.newInstance(button, i);
        

        @Override
        public int getCount()
        
            return 10;
        
    

    public static class ContainerFragment extends Fragment
    

        static ContainerFragment newInstance(int pos)
        
            ContainerFragment f = new ContainerFragment();
            Bundle args = new Bundle();
            args.putInt("pos", pos);
            f.setArguments(args);
            return f;
        

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        
            View rootView = inflater.inflate(R.layout.view_pager, container, false);
            ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
            MainPagerAdapter adapter = new MainPagerAdapter(getChildFragmentManager());
            adapter.button = getArguments().getInt("pos");
            pager.setAdapter(adapter);
            return rootView;
        

        // ---------------------------------------------------------------
        // HACK FIX für java.lang.IllegalStateException: No activity
        // ---------------------------------------------------------------

        private static final Field sChildFragmentManagerField;
        static
        
            Field f = null;
            try
            
                f = android.support.v4.app.Fragment.class.getDeclaredField("mChildFragmentManager");
                f.setAccessible(true);
            
            catch (NoSuchFieldException e)
            
            
            sChildFragmentManagerField = f;
        

        @Override
        public void onDetach()
        
            super.onDetach();

            if (sChildFragmentManagerField != null)
            
                try
                
                    sChildFragmentManagerField.set(this, null);
                
                catch (Exception e)
                
                
            
        
    

    public static class SubFragment extends Fragment
    
        static SubFragment newInstance(int button, int pos)
        
            SubFragment f = new SubFragment();
            Bundle args = new Bundle();
            args.putString("key", "Button " + button + "Fragment " + pos);
            f.setArguments(args);
            return f;
        

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        
            View rootView = inflater.inflate(R.layout.test_subfragment, container, false);
            ((TextView) rootView.findViewById(R.id.tv1)).setText(getArguments().getString("key"));
            return rootView;
        
    

为了完整起见,我也添加了 xml 文件:

test_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_
    android:layout_ >

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_
            android:layout_
            android:onClick="onClick"
            android:text="Button1" />

        <Button
            android:id="@+id/button2"
            android:layout_
            android:layout_
            android:onClick="onClick"
            android:text="Button2" />
    </LinearLayout>

</FrameLayout>

test_subfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv1"
    android:layout_
    android:layout_
    android:gravity="center"
    android:textSize="50sp" />

view_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/llContainer"
    android:layout_
    android:layout_
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_
        android:layout_ />

</LinearLayout>

【问题讨论】:

发布您的布局文件,以便我试用。 ;-) 这就是我刚刚在做的... :-) 【参考方案1】:

在主 Activity 的布局中添加一个额外的 FrameLayout。这是放置 Fragment 的位置。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main"
    android:layout_
    android:layout_ >

    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_
            android:layout_
            android:onClick="onClick"
            android:text="Button1" />

        <Button
            android:id="@+id/button2"
            android:layout_
            android:layout_
            android:onClick="onClick"
            android:text="Button2" />
 <!-- add this -->
        <FrameLayout
            android:id="@+id/fragment_frame"
            android:layout_
            android:layout_ >

        </FrameLayout>

    </LinearLayout>

</FrameLayout>

由于您将片段添加到 BackStack无需保存它们的实例。这就是您的应用程序崩溃的原因。调整你的onClick()方法如下:

    @Override
    public void onClick(View v)
    
        Fragment nextFragment = null;
        String nextFragmentTag = null;
        if (v.getId() == R.id.button1)
        
            nextFragment = ContainerFragment.newInstance(1);
            nextFragmentTag = "fragment1";
        
        else if (v.getId() == R.id.button2)
        
            nextFragment = ContainerFragment.newInstance(2);
            nextFragmentTag = "fragment2";
        

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_frame, nextFragment, nextFragmentTag);
        transaction.addToBackStack(null);
        transaction.commit();
    

我测试了代码。使用按钮更改片段有效,并且 保留 ViewPager 返回时的状态

【讨论】:

是的,我在再次显示片段时崩溃了......第一次它工作正常......我正在阅读并尝试两天以使其以某种方式工作。 .. 是的,我知道(虽然我不是 100% 确定,但我认为,我看到它崩溃了,但我现在无法重现它......所以我可能记错了)无论如何,问题是,我需要这一切在一个地方,我根本不知道页数......所以我真的更喜欢 FragmentPagerStateAdapter...... 好吧,我设法让它工作了。我正在使用 FragmentStatePagerAdapter。由于无论如何您都将片段添加到后台堆栈,因此无需保存它们的实例。请参阅我的更新答案。 你是对的,没有看到那个逻辑错误......这似乎解决了问题......刚刚测试了它。非常感谢您帮助我并花时间帮助我 这不会导致很多 ContainerFragment 实例永远不会被清理吗?我想如果你已经(通过替换)向片段管理器添加了一个片段,你应该通过标签查找它并重用它而不是每次都创建一个新实例?

以上是关于Fragment 和 FragmentStatePagerAdapter 中带有 ViewPager 的片段导致异常(带有完整示例)的主要内容,如果未能解决你的问题,请参考以下文章

Android Fragment使用 Activity, Fragment, WebView的状态保存和恢复

android--------实现Activity和Fragment通信的面向对象的万能接口

android fragment和activity的区别

Fragment常见问题

Fragment常见问题

Fragment常见问题