Android 从同样需要显示的片段初始化ViewPager/PagerAdapter

Android 从同样需要显示的片段初始化ViewPager/PagerAdapter,android,xamarin,xamarin.android,android-viewpager,fragmentstatepageradapter,Android,Xamarin,Xamarin.android,Android Viewpager,Fragmentstatepageradapter,我有一个片段(HomeFragment),它在工具栏中包含两个选项卡。我正在使用ViewPager和FragmentStatePagerAdapter内部HomeFragment使在片段之间滑动成为可能。但是,第一个选项卡应该显示承载ViewPager和PagerAdapter的片段(HomeFragment)。第二个选项卡应该显示另一个名为ChatFragment的片段 现在我的问题是显示了第二个选项卡,我确实可以从第一个选项卡滑动到第二个选项卡。但是第一个选项卡没有显示HomeFragmen

我有一个片段(
HomeFragment
),它在工具栏中包含两个选项卡。我正在使用
ViewPager
FragmentStatePagerAdapter
内部
HomeFragment
使在片段之间滑动成为可能。但是,第一个选项卡应该显示承载
ViewPager
PagerAdapter
的片段(
HomeFragment
)。第二个选项卡应该显示另一个名为
ChatFragment
的片段

现在我的问题是显示了第二个选项卡,我确实可以从第一个选项卡滑动到第二个选项卡。但是第一个选项卡没有显示
HomeFragment
应该在哪里的任何内容,它只是空的

我曾尝试将
ViewPager
pagerdapter
与另一个项目中的工具栏连接起来,效果非常好。然而,最大的区别在于
ViewPager
PagerAdapter
托管在活动内部,而现在
ViewPager
PagerAdapter
托管在需要显示的片段之一内部

所以我认为这可能与
ViewPager
/
PagerAdapter
托管在一个也需要显示的片段中有关

总之,如何从需要显示的片段之一托管ViewPager/FragmentStatePagerAdater?

有什么想法吗?如果有什么不清楚的地方,请告诉我

编辑:正如Stanislav Bondar指出的,这听起来有点像另一个(如何在android中将viewpager放入片段中?)。然而,据我所知,OP想知道如何使用带有嵌套片段的ViewPager。我没有嵌套片段,需要将ViewPager托管在单个片段中。

编辑2:代码。

Home.axml:


据我所知,您正在
主页片段中创建
查看页面
,然后将自己放入
查看页面
?接受答案的可能副本是使用嵌套片段。有没有其他方法可以在片段中托管ViewPager?请发布您的代码?这对我来说很好。@YorkShen代码现在发布了。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


  <android.support.design.widget.AppBarLayout
  android:id="@+id/appbar"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">


    <android.support.design.widget.CollapsingToolbarLayout
               android:id="@+id/collapsing_toolbar"
               android:layout_width="match_parent"
               android:layout_height="match_parent"
               app:layout_scrollFlags="scroll|snap"
               android:fitsSystemWindows="true"
               app:contentScrim="?attr/colorPrimary">

      <refractored.controls.CircleImageView
         android:id="@+id/circleProfileImage"
         android:layout_width="96dp"
         android:layout_height="96dp"
         android:src="@drawable/profile"
         android:layout_marginTop="15dp"
         android:layout_marginBottom="10dp"
         android:layout_gravity="center"
         app:civ_border_width="2dp"
         app:civ_border_color="#FF0000"/>


      <!--app:layout_collapseMode="pin" pins the icons when scrolling-->
      <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            app:layout_collapseMode="pin"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <!--Toolbar title -->
        <TextView
          android:id="@+id/toolbar_title"
          android:textStyle="bold"
          android:textColor="@color/white"
          android:textSize="18dp"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="start"/>

      </android.support.v7.widget.Toolbar>



    </android.support.design.widget.CollapsingToolbarLayout>


        <!-- -->
           <android.support.design.widget.TabLayout
               android:id="@+id/tabLayout"
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               app:tabTextColor="@color/black"
               app:tabSelectedTextColor="@color/gray"
               app:tabIndicatorColor="@color/accent"
               app:tabIndicatorHeight="6dp"
               app:tabMode="fixed"
               app:tabGravity="fill"/>

  </android.support.design.widget.AppBarLayout>


  <!--THIS VIEW WILL BE PINNED-->
  <android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


          <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                app:layout_behavior="@string/appbar_scrolling_view_behavior"
                android:scrollbars="vertical"
                android:clipToPadding="false"
                android:requiresFadingEdge="vertical"
                android:fadingEdgeLength="10dp"/>

          <!-- FLOATING ACTION BUTTON  --> 
          <android.support.design.widget.FloatingActionButton
              android:id="@+id/newBetFab"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_marginRight="20dp"
              android:layout_marginBottom="40dp"
              android:layout_gravity="bottom|end"
              android:src="@drawable/icon_add"
              app:fabSize="mini"
              app:backgroundTint="@color/accent"
              app:rippleColor="@color/primary"
              app:pressedTranslationZ="10dp"
              app:elevation="15dp"
              app:borderWidth="0dp"/>
   </android.support.v4.view.ViewPager>



</android.support.design.widget.CoordinatorLayout> 
using System;
using Android.App;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using SupportFragment = Android.Support.V4.App.Fragment;
using System.Collections.Generic;
using Refractored.Controls;
using App.Adapters;
using static App.MainActivity;
using IN.Galaxyofandroid.Spinerdialog;
using Android.Support.V4.View;

/// <summary>
/// This screen shows a view of the last conversations made by the user
/// </summary>

namespace App.Fragments
{
    public class HomeFragment : SupportFragment, IRecyclerAdapterCallback, IOnSpinerItemClick
    {
        private CircleImageView circleImage;
        private FloatingActionButton mFAB;
        private CoordinatorLayout mCoordLayout;
        private RecyclerView mRecyclerView;
        private RecyclerView.LayoutManager mLayoutManager;
        private RecyclerView.Adapter mAdapter;
        public static List<Bet> mBets { get; private set; }
        private TabLayout mTabLayout;
        private CircleImageView mCircleProfileImage;
        private FloatingActionButton mNewBetFAB;
        private SpinnerDialog mSpinnerDialog;
        private List<string> spinnerItems;
        private View view;



        public override void OnCreate(Bundle savedInstanceState)
        {
            HasOptionsMenu = true;

            base.OnCreate(savedInstanceState);

            // Create your fragment here
        }

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


            TextView toolbarTitle = view.FindViewById<TextView>(Resource.Id.toolbar_title);
            toolbarTitle.Text = Application.Context.GetString(Resource.String.ApplicationName);

            // **************************************************************
            //TABS
            mTabLayout = view.FindViewById<TabLayout>(Resource.Id.tabLayout);
            mTabLayout.AddTab(mTabLayout.NewTab().SetText("Chats"));
            mTabLayout.AddTab(mTabLayout.NewTab().SetText("Bets"));
            mTabLayout.AddTab(mTabLayout.NewTab().SetText("Ka-ching"));


            mRecyclerView = view.FindViewById<RecyclerView>(Resource.Id.recyclerView);

            //Create our layout manager
            mLayoutManager = new LinearLayoutManager(Application.Context);
            mRecyclerView.SetLayoutManager(mLayoutManager);
            mBets = new List<Bet>();


            mBets.Add(new Bet() { BetName = "Tom Hanks", Message = "Jeg tror jeg vinner", Date = "25.01.17" });
            mBets.Add(new Bet() { BetName = "Ellen DeGeneres", Message = "Jeg tror jeg vinner", Date = "04.03.17" });

            mBets.Add(new Bet() { BetName = "Barack Hussain Obama", Message = "Wanna guess who won?", Date = "04.03.17", ProfilePicture = Resource.Drawable.obama });
            mBets.Add(new Bet() { BetName = "Tom Hanks", Message = "Run, forest. Run!", Date = "25.01.17", ProfilePicture = Resource.Drawable.profile });
            mBets.Add(new Bet() { BetName = "Ellen DeGeneres", Message = "Be kind with one another", Date = "04.03.17", ProfilePicture = Resource.Drawable.profile });
            mBets.Add(new Bet() { BetName = "President Obama", Message = "Yes, we can!", Date = "25.01.17", ProfilePicture = Resource.Drawable.obama});
            mBets.Add(new Bet() { BetName = "Bernie Sanders", Message = "I'm a progressive", Date = "04.03.17", ProfilePicture = Resource.Drawable.bernie });
            mAdapter = new RecyclerAdapter(mBets, mRecyclerView, this);
            mRecyclerView.SetAdapter(mAdapter);


            mCircleProfileImage = view.FindViewById<CircleImageView>(Resource.Id.circleProfileImage);
            mCircleProfileImage.Click += (o, e) =>
            {
                //mCircleProfileImage.BorderColor = Resource.Color.lightgray;
                Console.WriteLine("Go to settings..");
                ReplaceFragment(new SettingsFragment(), null);
            };


            //**************************************
            // Searchable spinner (list of users)
            InitSpinnerItems(mBets);



            //***************************************
            // FAB - Create a new bet
            mNewBetFAB = view.FindViewById<FloatingActionButton>(Resource.Id.newBetFab);
            mNewBetFAB.Click += delegate 
            {
                mSpinnerDialog = new SpinnerDialog(Activity, spinnerItems, "Choose friend");
                mSpinnerDialog.BindOnSpinerListener(this);
                mSpinnerDialog.ShowSpinerDialog();

            };


            //Viewpager
            ViewPager viewPager = view.FindViewById<ViewPager>(Resource.Id.viewpager);
            PagerAdapter pagerAdapter = new TabsPagerAdapter(Activity.SupportFragmentManager);
            viewPager.Adapter = pagerAdapter;
            mTabLayout.SetupWithViewPager(viewPager);



            return view;
        }



        /// <summary>
        /// Callback function that is called when user has pressed on one of the conversations in the RecyclerAdapter
        /// </summary>
        /// <param name="position"></param>
        public void OnMethodCallback(int position)
        {
            ReplaceFragment(new ChatFragment(), null);
        }

        public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
        {

            //Activity.MenuInflater.Inflate(Resource.Menu.overflow_menu, menu);
            //Activity.OnCreateOptionsMenu(menu);
            inflater.Inflate(Resource.Menu.overflow_menu, menu);
            base.OnCreateOptionsMenu(menu, inflater);
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {

            switch (item.ItemId)
            {
                case Resource.Id.action_add:
                    //mBets.Add(new Bet() { BetName = "Steinar Ragnarok", Message = "Jeg tror jeg vinner", Date = "30.06.17" });
                    //mAdapter.NotifyItemInserted(0);     //notify adapter that item was inserted at the head (pos 0)
                    ReplaceFragment(new ChatFragment(), null);
                    return true;
                case Resource.Id.action_search:
                    //Toast.MakeText(Application.Context, "You clicked on search", ToastLength.Short).Show();
                    return false;
                case Resource.Id.action_settings:
                    //Toast.MakeText(Application.Context, "You clicked on search", ToastLength.Short).Show();
                    return false;

            }

            return base.OnOptionsItemSelected(item);
        }

        // Replace fragment
        private void ReplaceFragment(SupportFragment fragment, Bundle bundle)
        {
            if (Globals.mCurrentFragment.Equals(fragment))
            {
                Toast.MakeText(Application.Context, "You're already in that menu.", ToastLength.Short).Show();
                return;
            }

            var trans = FragmentManager.BeginTransaction();

            //set animation (including animation for 'back' button)
            trans.SetCustomAnimations(Resource.Animation.abc_grow_fade_in_from_bottom, Resource.Animation.abc_shrink_fade_out_from_bottom, Resource.Animation.abc_grow_fade_in_from_bottom, Resource.Animation.abc_shrink_fade_out_from_bottom);

            if (bundle != null)
                fragment.Arguments = bundle;

            trans.Replace(Resource.Id.fragmentContainer, fragment);                 // hide the current fragment
            trans.AddToBackStack(null);                                             // makes it possible to go back to the current fragment late
            trans.Commit();
            Globals.mStackFragment.Push(Globals.mCurrentFragment);                  // put fragment in back-stack before switching
            Globals.mCurrentFragment = fragment;                                    // update current fragment

        }


        private void InitSpinnerItems(List<Bet> betsList)
        {
            spinnerItems = new List<string>();
            foreach (Bet bet in betsList ){
                spinnerItems.Add(bet.BetName);
            }
        }

        /// <summary>
        /// What to do when SearchableSpinner is opened
        /// </summary>
        /// <param name="p0"></param>
        /// <param name="p1"></param>
        public void OnClick(string item, int position)
        {
            Bundle bundle = new Bundle();

            bundle.PutInt("spinner_chosen_position", position);
            ReplaceFragment(new CreateBetFragment(), bundle);
            Toast.MakeText(Activity, $"Nr {position}, {item}, was chosen.", ToastLength.Short).Show();
        }
    }
}
using System;
using Android.App;
using Android.Views;
using Java.Lang;
using Android.Support.V4.App;
using App.Fragments;

namespace App.Adapters
{
    public class TabsPagerAdapter : FragmentStatePagerAdapter
    {
        public TabsPagerAdapter(Android.Support.V4.App.FragmentManager fm) : base(fm)
        {

        }

        public override int Count
        {
            get { return 2; }
        }

        public override Android.Support.V4.App.Fragment GetItem(int position)
        {
            switch (position)
            {
                case 0:
                    return new HomeFragment();
                case 1:
                    return new ChatFragment();
                default:
                    throw new NotImplementedException();
            }
        }

        public override ICharSequence GetPageTitleFormatted(int position)
        {
            switch (position)
            {
                case 0:
                    return new Java.Lang.String(Application.Context.GetString(Resource.String.tab1_chats));
                case 1:
                    return new Java.Lang.String(Application.Context.GetString(Resource.String.tab2_bets));
                default:
                    return null;

            }
        }

    }
}