Android,PageView在重新创建活动后不显示片段

时间:2016-03-03 11:35:46

标签: android android-fragments

我正在使用Xamarin开发android。我有一个显示WebView的片段和一个显示带有2个选项卡的PageViewer的页面。一切正常,直到我在我的Android设备上激活开发者选项“不要保持活动”。当我启动我的应用程序并且我继续回家时,每一件事都没关系,所以我继续使用WebViewPage,我将应用程序发送到后台,我恢复它,WebViewPage正确显示,但是当我去Home(我使用的是导航抽屉),正确地重新创建选项卡,但片段是空白的。我真的不明白为什么..似乎没有调用OnCreateView,并且在重新创建的Activity之后不调用我的适配器的GetItem()。调试我看到了这个:系统首先调用这两个片段,但由于某种原因,当我重新创建我的标签时,片段是空白的。

这是我的代码:

MainActivity

namespace N****_AndroidOS {

[ Activity ( Label = "Niteko", /*LaunchMode = Android.Content.PM.LaunchMode.SingleInstance,*/ ScreenOrientation = ScreenOrientation.Portrait, Icon = "@drawable/icon" ) ]
public class MainActivity : AppCompatActivity {

    private NavigationView  m_nvNavigationView;
    private DrawerLayout    m_dlDrawerLayout;
    private Toolbar         m_tToolBar;

    /* Fragments */
    private CatalogShowerTabsFragment m_fCatalogWithTabShower;
    private WebViewPageFragment       m_fHowWeAre;
    private WebViewPageFragment       m_fTermsAndConds;
    private WebViewPageFragment       m_fInfoPrivacy;
    private SettingsFragment          m_fSettings;
    private ContactUsFragment         m_fContactUs;
    private NotificationFragment      m_fNotifications;

    protected override void OnCreate( Bundle bundle ) {
        base.OnCreate( bundle );

        SetContentView( Resource.Layout.activity_nav_drawer );

        SetupToolBar();

        m_dlDrawerLayout = (DrawerLayout)FindViewById( Resource.Id.nav_drawer );
        m_nvNavigationView   = FindViewById<NavigationView>( Resource.Id.nav_view );

        SupportActionBar.SetHomeAsUpIndicator( Resource.Drawable.ic_menu );
        SupportActionBar.SetDisplayHomeAsUpEnabled( true );

        SupportActionBar.SetDisplayUseLogoEnabled( true );
        SupportActionBar.SetLogo( Resource.Drawable.ic_icon_header );
        SupportActionBar.SetWindowTitle( Resources.GetString( Resource.String.title_home ) );

        m_nvNavigationView.NavigationItemSelected += (sender, e ) => {
            e.MenuItem.SetChecked( true );
            //react to click here and swap fragments or navigate

            ChangeFragment( e.MenuItem.ItemId );

            m_dlDrawerLayout.CloseDrawers();
        };


        m_nvNavigationView.Menu.GetItem( 0 ).SetChecked( true );

        m_fCatalogWithTabShower = null;
        m_fHowWeAre             = null;
        m_fTermsAndConds        = null;
        m_fInfoPrivacy          = null;
        m_fSettings             = null;
        m_fContactUs            = null;
        m_fNotifications        = null;


        if ( bundle == null ) {
            ChangeFragment( Resource.Id.nav_home );
        }
        else {

        }
    }


    private void ChangeFragment( int iMenuID, object iArg = null ) {

        RunOnUiThread( () => {
            // Create a new fragment and a transaction.
            Android.Support.V4.App.FragmentTransaction fragmentTx = (Android.Support.V4.App.FragmentTransaction) this.SupportFragmentManager.BeginTransaction();

            Android.Support.V4.App.Fragment fragmentToShow = null;

            bool isLogged = false;

            ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences( this ); 
            string eMail = prefs.GetString( ParamsInfo.PK_EMAIL, "" );

            if ( string.IsNullOrEmpty( eMail ) ) {
                isLogged = false;
            }
            else {
                isLogged = true;
            }

            switch ( iMenuID ) {
                case Resource.Id.nav_home:

                SupportActionBar.SetDisplayUseLogoEnabled( true );
                SupportActionBar.SetLogo( Resource.Drawable.Icon );
                SupportActionBar.SetWindowTitle( Resources.GetString( Resource.String.title_home ) );

                if ( m_fCatalogWithTabShower == null ) {
                    m_fCatalogWithTabShower = new CatalogShowerTabsFragment();
                }

                fragmentToShow = m_fCatalogWithTabShower;

                break;

                case Resource.Id.nav_howweare:

                SupportActionBar.SetDisplayUseLogoEnabled( false );
                SupportActionBar.SetWindowTitle( Resources.GetString( Resource.String.title_who ) );

                if ( m_fHowWeAre == null ) {
                    m_fHowWeAre = new WebViewPageFragment();
                    m_fHowWeAre.WebPageID = ParamsInfo.PK_STATIC_HOWWEARE;
                }

                //fragmentTx.AddToBackStack( null );

                fragmentToShow = m_fHowWeAre;
                break;

            }

            if ( fragmentToShow != null ) {
                // Replace the fragment that is in the View fragment_container (if applicable).
                fragmentTx.Replace( Resource.Id.nav_contentframe, fragmentToShow );

                // Add the transaction to the back stack.
                //fragmentTx.AddToBackStack( null );

                // Commit the transaction.
                fragmentTx.Commit();
            }

        } );

    }
}

调用CatalogShowerFragment以创建包含两个片段的页面浏览器

public class CatalogShowerTabsFragment : Android.Support.V4.App.Fragment  {

    private View    m_vView;
    private Adapter m_aViewPagerAdapter;
    private bool    m_bAlreadyFilled     = false;

    public override View OnCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
        // Use this to return your custom view for this Fragment
        // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

        if ( !m_bAlreadyFilled ) {
            m_vView = inflater.Inflate( Resource.Layout.CatalogWithTabShowerLayout, container, false );

            var viewPager = m_vView.FindViewById<Android.Support.V4.View.ViewPager>( Resource.Id.htab_viewpager );

            if ( viewPager != null ) {
                setupViewPager( viewPager );
            }

            TabLayout tabLayout = m_vView.FindViewById<TabLayout>( Resource.Id.htab_tabs );

            tabLayout.SetupWithViewPager( viewPager );

            m_bAlreadyFilled = true;
        }

        return m_vView;
    }

    public override void OnDestroy() {
        base.OnDestroy();

        AndroidHUD.AndHUD.Shared.Dismiss( Activity );
    }

    class Adapter : Android.Support.V4.App.FragmentPagerAdapter {

        List<V4Fragment> fragments      = new List<V4Fragment>();
        List<string>     fragmentTitles = new List<string>();

        public Adapter( V4FragmentManager fm ) : base ( fm ) {

        }

        public void AddFragment( V4Fragment fragment, string title ) {
            fragments.Add( fragment );
            fragmentTitles.Add( title );
        }

        public override V4Fragment GetItem( int position ) {
            return fragments[ position ];
        }

        public override int Count {
            get { return fragments.Count; }
        }

        public override Java.Lang.ICharSequence GetPageTitleFormatted( int position ) {
            return new Java.Lang.String( fragmentTitles[ position ] );
        }

    }

    /* Costruiamo la Tabbar per la selezione dei tipi di prodotti */
    private void setupViewPager( Android.Support.V4.View.ViewPager viewPager ) {

        if ( m_aViewPagerAdapter == null ) {
            m_aViewPagerAdapter = new Adapter( Activity.SupportFragmentManager );

            ItemsListCategoryFragment fragmentProduct = new ItemsListCategoryFragment();
            fragmentProduct.ListType = ItemsListCategoryFragment.LIST_CATEGORY.LC_PRODUCTS;

            ItemsListCategoryFragment fragmentApplications = new ItemsListCategoryFragment();
            fragmentApplications.ListType = ItemsListCategoryFragment.LIST_CATEGORY.LC_APPLICATIONS;

            m_aViewPagerAdapter.AddFragment( fragmentProduct, Resources.GetString( Resource.String.tab_productions_title ) );
            m_aViewPagerAdapter.AddFragment( fragmentApplications, Resources.GetString( Resource.String.tab_applications_title ) );

            viewPager.Adapter = m_aViewPagerAdapter;

            viewPager.Adapter.NotifyDataSetChanged();

        }
    }
}

最后是碎片。

public enum LIST_CATEGORY {
          LC_PRODUCTS
        , LC_APPLICATIONS
    }

    private LIST_CATEGORY                  m_enListType;
    private CategoryListResponseResult     m_clrResponseResult;
    private ItemsListCategoryShowerAdapter m_ilcCatergoryAdapter;
    private List<CategoryModel>            m_lCategoryModelList;
    private Task                           m_tTask;
    private View                           m_vView;

    //Pull to refresh
    private PullToRefresharp.Android.Widget.ListView m_lListView;

    /* params */
    private int  m_iCurrentPage  = 0;
    private int  m_iPageLimit    = 10;
    private bool m_bFirstTime    = true;
    private bool m_bNoMoreElem   = false;

    public static bool pezza = false;

    public LIST_CATEGORY ListType {
        set { m_enListType = value; }
        get { return m_enListType;  }
    }

    public ItemsListCategoryFragment( /*LIST_CATEGORY iListType*/ ) {
        m_enListType = LIST_CATEGORY.LC_APPLICATIONS;  //iListType;
        m_tTask      = Task.Factory.StartNew( () => {} );

    }

    public override void OnActivityCreated( Bundle savedInstanceState ) {
        base.OnActivityCreated( savedInstanceState );
    }

    public override void OnCreate( Bundle savedInstanceState ) {
        base.OnCreate( savedInstanceState );
    }

    public override View OnCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {

        pezza = true;

        if ( savedInstanceState != null ) {
            m_enListType = (LIST_CATEGORY)( savedInstanceState.GetInt( ParamsInfo.PK_CATTYPE ) );
        }

        if ( m_vView == null ) {   
            m_vView = inflater.Inflate( Resource.Layout.CatalogGeneralListLayout, container, false );

            m_lListView = m_vView.FindViewById<PullToRefresharp.Android.Widget.ListView>( Resource.Id.lwMyEventsPullToRefresh );
            m_lListView.RefreshActivated += RefreshMyContent;

            m_lListView.ItemClick += OnListItemClick;

            m_lListView.ScrollStateChanged += (sender, e) => {
                OnScrollStateChange( e.ScrollState );
            };

            GetAndFillListFromNetwork();
        }

        return m_vView;
    }

    public override void OnResume() {
        base.OnResume();
    }

    private void RefreshMyContent( object sender, EventArgs e ) {

        Activity.RunOnUiThread( () => {

            m_iCurrentPage = 0;
            m_bNoMoreElem  = false;
            m_bFirstTime   = true;

            GetAndFillListFromNetwork();

            m_lListView.OnRefreshCompleted();

        } );
    }

    public override void OnDestroy() {
        base.OnDestroy();

        AndroidHUD.AndHUD.Shared.Dismiss( Activity );
    }

    private void GetAndFillListFromNetwork() {

        //AndHUD.Shared.Show( Activity, Resources.GetString( Resource.String.loading ) );

        AndHUD.Shared.ShowToast( Activity, Resources.GetString( Resource.String.loading ), (MaskType)3, default(TimeSpan?), false );
        m_tTask = m_tTask.ContinueWith( t => {

            InformationData infoData = new InformationData();
            if ( m_enListType == LIST_CATEGORY.LC_PRODUCTS ) {
                infoData.AddParam( ParamsInfo.PK_CATTYPE, "0" ); //0: prodotti 1: applicazioni
            }
            else {
                infoData.AddParam( ParamsInfo.PK_CATTYPE, "1" );
            }

            infoData.AddParam( ParamsInfo.PK_PAGENUM, m_iCurrentPage.ToString() );
            infoData.AddParam( ParamsInfo.PK_PAGELIMIT, "10" );

            m_clrResponseResult = (CategoryListResponseResult)FrontController.Instance.Execute( CommandType.COMMANDREQUEST.CR_ASYNC_GETCATEGORY, infoData );

            Activity.RunOnUiThread( () => {

                AndHUD.Shared.Dismiss( Activity );

                switch ( m_clrResponseResult.Status ) {
                    case ResponseResult.RESPONDSTATUS.RS_SUCCESS:

                        if ( m_bFirstTime ) {
                            m_bFirstTime = false;

                            m_lCategoryModelList  = new List<CategoryModel>();
                            m_lCategoryModelList.AddRange( m_clrResponseResult.data.categories );

                            m_ilcCatergoryAdapter = new ItemsListCategoryShowerAdapter( Activity, m_lCategoryModelList );
                            m_lListView.Adapter   = m_ilcCatergoryAdapter;

                        }
                        else {
                            m_lCategoryModelList.AddRange( m_clrResponseResult.data.categories );
                        }

                        if ( m_clrResponseResult.data.categories.Count < m_iPageLimit ) {
                            m_bNoMoreElem = true;
                        }

                        m_ilcCatergoryAdapter.NotifyDataSetChanged();

                    break;
                    case ResponseResult.RESPONDSTATUS.RS_CONNECTION_ERROR:
                    PerformConnectionLost();
                    break;
                }
            } );
       } );
    }

    public override void OnSaveInstanceState( Bundle outState ) {

        outState.PutInt( ParamsInfo.PK_CATTYPE, (int)m_enListType );

        base.OnSaveInstanceState( outState );
    }

    private void PerformConnectionLost() {
        AndHUD.Shared.ShowError( Activity, Resources.GetString( Resource.String.err_connection_lost ), MaskType.None, new TimeSpan( 90, 90, 90, 90 ), OnOkMessageClick );
    }

    private void OnOkMessageClick() {
        GetAndFillListFromNetwork();
    }

    private void OnListItemClick( object iSender, AdapterView.ItemClickEventArgs iEvent ) {

        CategoryModel cm = m_lCategoryModelList[ iEvent.Position ];

        Intent itemsDetailsActivity = new Intent( Activity, typeof( ItemsListDetailsActivity ) );
        itemsDetailsActivity.PutExtra( ParamsInfo.PK_CAT_ID, cm.id );
        itemsDetailsActivity.PutExtra( ParamsInfo.PK_CAT_TITLE, cm.label );
        itemsDetailsActivity.PutExtra( ParamsInfo.PK_IMG_URL, cm.img );

        if ( m_enListType == LIST_CATEGORY.LC_APPLICATIONS ) {
            itemsDetailsActivity.PutExtra( ParamsInfo.PK_HEADER_TITLE, Resources.GetString( Resource.String.title_applications ) );
        }
        else {
            itemsDetailsActivity.PutExtra( ParamsInfo.PK_HEADER_TITLE, Resources.GetString( Resource.String.title_products ) );
        }

        StartActivity( itemsDetailsActivity );

    }

    protected void OnScrollStateChange( ScrollState iScrollState ) {

        if ( iScrollState == ScrollState.Idle ) {
            if ( m_lListView.LastVisiblePosition == m_lListView.Adapter.Count - 1 ) {

                /* richiamo i prossimi elementi */
                if ( !m_bNoMoreElem ) {
                    ++m_iCurrentPage;
                    GetAndFillListFromNetwork();
                }
            }
        }
    }
}

我真的无法理解为什么当我重新创建我的活动时这不起作用..似乎片段已经由系统默认创建了,但是我强迫我自己用一个新的页面浏览器重新构建,所以为什么碎片不显示?重建应用程序后,其他部分中的每个其他片段都会显示没有问题。

谢谢你。

1 个答案:

答案 0 :(得分:0)

使用 FragmentStatePagerAdapter 代替 FragmentPagerAdapter ,一切正常!该死的机器人!!