简体   繁体   English

所有片段都在活动时加载

[英]all fragments are loading at time of activity

I am very...very new to android development and I am trying to recreate a hybrid app I built in ionic, but do it in actual android. 我对Android开发非常陌生,我正在尝试重新创建我在ionic中构建的混合应用程序,但要在实际的android中进行。 I am having an issue with either layouts or fragment loading that I can't figure out. 我在布局或片段加载方面遇到了无法解决的问题。 What I want is something similar to the IG layout, where there is a bar at the bottom for navigation, clicking the button would load the new page. 我想要的是类似于IG布局的内容,在该页面的底部有一个导航栏,单击该按钮将加载新页面。 From my understanding the best way to accomplish that is to use a main activity, then each of the tabs at the bottom are fragments. 根据我的理解,完成此任务的最佳方法是使用主要活动,然后底部的每个选项卡都是片段。 So I built that, but I want the top toolbar to disappear on the second tab, so in the second tab "onCreateView" method I added the toolbar.setVisibility(View.GONE); 因此,我构建了该控件,但是我希望顶部的工具栏在第二个选项卡上消失,因此在第二个选项卡的“ onCreateView”方法中,添加了toolbar.setVisibility(View.GONE);。 however, as soon as I load the app, even on the first tab, the toolbar at the top is gone, signifying it is loading the views for each fragment when the app loads. 但是,一旦我加载了应用程序,即使在第一个选项卡上,顶部的工具栏也消失了,这表明它在应用程序加载时正在为每个片段加载视图。 I would think that would severely impact performance on a large app. 我认为这将严重影响大型应用程序的性能。 Am I crazy? 我疯了吗? Here is my main layout for the main 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>

Then my HomeActivity class.. 然后是我的HomeActivity类。

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

    }

}

So, in the "ProfileFragment" in the onCreateView method I have... 因此,在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;
    }

As you can see I am setting the visibility for the toolbar from the HomeActivity to View.GONE, however, the toolbar is gone from all fragments now. 如您所见,我将工具栏的可见性从HomeActivity设置为View.GONE,但是,该工具栏现在已从所有片段中删除。 I just want a bottom navigation setup with a top toolbar that can be hidden when certain fragments load, but is visible in other fragments. 我只想要一个带有顶部工具栏的底部导航设置,可以在加载某些片段时将其隐藏,但在其他片段中可见。 Is that even possible? 那有可能吗? Thank you. 谢谢。

You can control the numbers of fragments loading in view pager by simply using this method: 您可以使用以下方法控制在视图分页器中加载的片段数:

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

you can increase or decrease the number of fragments loading according to your requirements but atleast 1. 您可以根据需要增加或减少片段加载的数量,但至少为1。

hope this will help you. 希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM