所有片段都在 activity 时加载

all fragments are loading at time of activity

我对 android 开发非常...非常陌生,我正在尝试重新创建一个我在 ionic 中构建的混合应用程序,但在实际 android 中进行。 我遇到无法弄清楚的布局或片段加载问题。 我想要的是类似于IG布局的东西,底部有一个导航栏,点击按钮会加载新页面。根据我的理解,实现该目标的最佳方法是使用主 activity,然后底部的每个选项卡都是片段。 所以我构建了它,但我希望顶部工具栏在第二个选项卡上消失,所以在第二个选项卡 "onCreateView" 方法中我添加了 toolbar.setVisibility(View.GONE);但是,一旦我加载应用程序,即使在第一个选项卡上,顶部的工具栏也消失了,这表明它正在加载应用程序加载时每个片段的视图。我认为这会严重影响大型应用程序的性能。我疯了吗? 这是我主要 activity...

的主要布局
<?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>

然后我的HomeActivityclass..

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;
        }

    }

}

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

 @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.GONE,但是,工具栏现在从所有片段中消失了。我只想要一个带有顶部工具栏的底部导航设置,该工具栏可以在某些片段加载时隐藏,但在其他片段中可见。这可能吗?谢谢。

您可以通过简单地使用此方法来控制在视图分页器中加载的片段数:

  viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.

您可以根据需要增加或减少片段加载数量,但至少 1 个。

希望对您有所帮助。