Java 所有片段都在活动时加载

Java 所有片段都在活动时加载,java,android,android-fragments,android-toolbar,Java,Android,Android Fragments,Android Toolbar,我对android开发非常……非常陌生,我正在尝试重新创建一个我在爱奥尼亚(ionic)中构建的混合应用程序,但在实际的android中实现它。 我有一个布局或片段加载的问题,我不能弄清楚。 我想要的是类似于IG布局的东西,在底部有一个用于导航的栏,单击按钮将加载新页面。根据我的理解,最好的方法是使用一个主活动,然后底部的每个选项卡都是片段。 因此,我构建了它,但我希望顶部工具栏在第二个选项卡上消失,因此在第二个选项卡onCreateView方法中,我添加了toolbar.setVisibili

我对android开发非常……非常陌生,我正在尝试重新创建一个我在爱奥尼亚(ionic)中构建的混合应用程序,但在实际的android中实现它。 我有一个布局或片段加载的问题,我不能弄清楚。 我想要的是类似于IG布局的东西,在底部有一个用于导航的栏,单击按钮将加载新页面。根据我的理解,最好的方法是使用一个主活动,然后底部的每个选项卡都是片段。 因此,我构建了它,但我希望顶部工具栏在第二个选项卡上消失,因此在第二个选项卡onCreateView方法中,我添加了toolbar.setVisibilityView.GONE;然而,当我加载应用程序时,即使在第一个选项卡上,顶部的工具栏也不见了,这意味着在加载应用程序时,它正在加载每个片段的视图。我认为这会严重影响大型应用程序的性能。我疯了吗? 这是我的主要活动的主要布局

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/main_layout">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="@color/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    <android.support.v4.view.ViewPager
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/toolbar" />
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        app:tabSelectedTextColor="#FFFFFF"
        app:tabTextColor="#D3D3D3"
        app:tabIndicatorColor="#FF00FF"
        android:minHeight="?attr/actionBarSize"
        android:layout_alignParentBottom="true" />
</RelativeLayout>
然后我的家庭活动课

public class HomeActivity extends BaseActivity implements OnFragmentTouched {

    private TextView mTextMessage;

    private static final String SELECTED_ITEM = "arg_selected_item";
    private int                  mSelectedItem;
    private BottomNavigationView mBottomNav;

    private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();



    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mSelectedItem);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        MenuItem homeItem = mBottomNav.getMenu().getItem(0);
        if (mSelectedItem != homeItem.getItemId()) {
            // select home item
            selectFragment(homeItem);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        ViewPager pager = (ViewPager) findViewById(R.id.content);

        PagerAdapter pagerAdapter = (PagerAdapter) new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);

        pager.setAdapter(pagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(pager);

        for(int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }
    }

    private void selectFragment(MenuItem item) {
        Fragment frag = null;
        switch(item.getItemId()) {
            case R.id.navigation_home:
                frag = new AllPostsFragment();
                break;
            case R.id.navigation_dashboard:
                frag = ProfileFragment.newInstance(user.getUid());
                break;
            case R.id.navigation_notifications:
                frag = new ChatListFragment();
                break;
        }
        mSelectedItem = item.getItemId();

    }

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }

    @Override
    public void onFragmentTouched(Fragment fragment, float x, float y) {
        Log.d("FRAGMENT_TOUCHED", "The ChatListFragment touch happened");
        if(fragment instanceof ChatFragment) {
            final ChatFragment theFragment = (ChatFragment) fragment;

            Animator unreveal = theFragment.prepareUnrevealAnimator(x, y);

            unreveal.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    getSupportFragmentManager().beginTransaction().remove(theFragment).commit();
                    getSupportFragmentManager().executePendingTransactions();
                }

                @Override
                public void onAnimationCancel(Animator animation) {}
                @Override
                public void onAnimationRepeat(Animator animation) {}
            });
            unreveal.start();
        }
    }


    public String getUid() {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        Context context;

        String tabTitles[] = new String[] {"Home", "Profile", "Chat"};

        public PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public Fragment getItem(int pos) {
            switch(pos) {
                case 0: return new AllPostsFragment();
                case 1: return ProfileFragment.newInstance(user.getUid());
                case 2: return new ChatListFragment();
                default:
                    return new AllPostsFragment();
            }
        }

        @Override
        public int getCount() {
            return tabTitles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabTitles[position];
        }

        public View getTabView(int position) {
            View tab = LayoutInflater.from(HomeActivity.this).inflate(R.layout.custom_tab, null);
            TextView tv = (TextView) tab.findViewById(R.id.custom_text);
            tv.setText(tabTitles[position]);
            return tab;
        }

    }

}
所以,在onCreateView方法中的ProfileFragment中,我有

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.userPostsRecycler);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(layoutManager);

        Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
        toolbar.setVisibility(View.GONE);
        followingCountText = rootView.findViewById(R.id.following_count);
        followersCountText = rootView.findViewById(R.id.followers_count);
        titleLayout = rootView.findViewById(R.id.toolbar_layout);

        titleLayout.setTitle(user.getDisplayName());

        fab1Container = rootView.findViewById(R.id.fab_1);
        fab2Container = rootView.findViewById(R.id.fab_2);



        ImageView profilePhoto = (ImageView) rootView.findViewById(R.id.profile_photo);

        Glide.with(this).load(user.getPhotoUrl()).into(profilePhoto);


        fabContainer = (LinearLayout) rootView.findViewById(R.id.fabContainerLayout);
        fab = (FloatingActionButton) rootView.findViewById(R.id.profile_fab);
        instigatingFab = fab;
        fabBaseX = fab.getX();
        fabBaseY = fab.getY();
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBlurredDialog();
            }
        });

        progressDialog = new ProgressDialog(getContext());

        uploads = new ArrayList<>();

        progressDialog.setMessage("Please wait...");
        progressDialog.show();

        DatabaseReference followersDB = FirebaseDatabase
                .getInstance()
                .getReference("followers")
                .child(user.getUid())
                .child("count");
        followersDB.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int followersCount = dataSnapshot.getValue(Integer.class);
                followersCountText.setText(Integer.toString(followersCount));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        DatabaseReference followingReference = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("users");
        followingReference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        DatabaseReference followingDB = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("count");
        followingDB.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int followingCount = dataSnapshot.getValue(Integer.class);
                followingCountText.setText(Integer.toString(followingCount));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        mDatabase = FirebaseDatabase.getInstance().getReference("/userPosts").child(user.getUid()).child("posts");

        mDatabase.limitToFirst(25).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                progressDialog.dismiss();

                for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    String postID = postSnapshot.getKey();
                    uploads.add(postID);
                }
                uploads.add("-KtvzkOL_75wiKA4CMsr");


                adapter = new ProfileUserPostsViewHolder(getContext(), uploads);

                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                progressDialog.dismiss();
            }
        });
        return rootView;
    }

如您所见,我正在将工具栏的可见性从HomeActivity设置为View.Goe,但是,工具栏现在已从所有片段中消失。我只想要一个带有顶部工具栏的底部导航设置,当某些片段加载时可以隐藏,但在其他片段中可见。这可能吗?谢谢。

您只需使用以下方法即可控制在view pager中加载的片段数:

  viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.
您可以根据需要增加或减少加载的片段数量,但至少为1


希望这能对您有所帮助。

太棒了。非常感谢。@Zohrakan设置为可能是2,我不知道确切的数字。@NoumanCh Android文档明确说明屏幕外页面限制默认值为1。