viewpager没有在第一次加载第一页,但会在刷到最后一页后加载它

时间:2016-07-20 01:55:27

标签: android

我是Android开发的新手,我没有太多的SO币。 基本上,我的项目有一个主屏幕活动,它包含3个选项卡,分别是MyGiftsFragment,FriendsGiftsFragment和AboutMeFragment。我在这里实现了tablayout和viewpager。问题是,当我登录应用程序时,第一页(MyGiftsFragment)为空,没有加载任何内容(有时它已加载。)但是当我刷到最后一个选项卡(AboutMeFragment)并返回第一个选项卡时,内容将会加载。这只有在我刷到最后一个标签时才有效。

由于我的英语限制,我不确定我是否清楚地解释了这个问题。如果您需要任何进一步的信息,请发表评论。我搜索了“setUserVisibleHint”和“setOnPageChangeListener(pageChangeListener)”,但似乎它们不是我想要的。任何建议将被认真考虑。非常感谢你。

以下是我的MainScreenActivity代码。

public class MainScreenActivity extends AppCompatActivity {

    private static final String TAG = MainScreenActivity.class.getName();
    FirebaseAuth mAuth;
    private DrawerLayout mDrawerLayout;
    private FloatingActionButton fab;
    private ArrayList<Gift> mGiftArray;
    private RecyclerView mRecyclerView;
    private boolean doubleBackToExitPressedOnce = false;

    private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplication().getApplicationContext());
        mAuth = FirebaseAuth.getInstance();

        setContentView(R.layout.activity_main_screen);
        /** Setup Toolbar and ActionBar. */
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        actionBar.setDisplayHomeAsUpEnabled(true);

        /** Setup DrawerLayout. */
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);

        /** 1.Setup drawer header content: Title and profile picture. */
        View drawerHeader = navigationView.getHeaderView(0);
        NetworkImageView drawerPicture = (NetworkImageView) drawerHeader.findViewById(R.id.drawer_picture);
        NetworkImageView coverPicture = (NetworkImageView) drawerHeader.findViewById(R.id.cover_picture);

        /** Fetch data from SharePreferences. */
        SharedPreferences mSharedPreferences = this.getSharedPreferences("test", Activity.MODE_PRIVATE);
        String drawerPictureUrl = mSharedPreferences.getString("picture", "");
        String coverPictureUrl = mSharedPreferences.getString("cover", "");
        ImageLoader imageLoader = MySingleton.getInstance(MainScreenActivity.this.getApplicationContext()).getImageLoader();
        drawerPicture.setImageUrl(drawerPictureUrl, imageLoader);
        coverPicture.setImageUrl(coverPictureUrl, imageLoader);


        /** 2.Setup drawer body content: Name, E-mail and birthday. */
        /** Fetch data from SharePreferences. */
        String username = mSharedPreferences.getString("username", "");
        String email = mSharedPreferences.getString("email", "");
        String birthday = mSharedPreferences.getString("birthday", "");
        Menu menu = navigationView.getMenu();
        MenuItem nav_name = menu.findItem(R.id.navigation_item_name);
        nav_name.setTitle(username);
        MenuItem nav_email = menu.findItem(R.id.navigation_item_email);
        nav_email.setTitle(email);
        MenuItem nav_birthday = menu.findItem(R.id.navigation_item_birthday);
        nav_birthday.setTitle(birthday);

        /** Setup item onSelectedListener. */
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                Intent intent;

                if (menuItem.getItemId() == R.id.navigation_item_name) {
                    mDrawerLayout.closeDrawers();
                    intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
                    startActivity(intent);
                    return true;
                }

                if (menuItem.getItemId() == R.id.navigation_item_email) {
                    mDrawerLayout.closeDrawers();
                    intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
                    startActivity(intent);
                    return true;
                }

                if (menuItem.getItemId() == R.id.navigation_item_birthday) {
                    mDrawerLayout.closeDrawers();
                    intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
                    startActivity(intent);
                    return true;
                }

                if (menuItem.getItemId() == R.id.navigation_item_payment) {
                    mDrawerLayout.closeDrawers();
                    intent = new Intent(MainScreenActivity.this, AddGiftsActivity.class);
                    startActivity(intent);
                    return true;
                }

                if (menuItem.getItemId() == R.id.navigation_item_refresh) {
                    mDrawerLayout.closeDrawers();
                    finish();
                    startActivity(getIntent());
                    return true;
                }

                if (menuItem.getItemId() == R.id.navigation_item_logout) {

                    mDrawerLayout.closeDrawers();

                    facebookLogout();
                    return true;
                }
                return false;
            }
        });

        /** Setup FloatingActionButton. */
        fab = (FloatingActionButton)findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Context context = view.getContext();
                Intent intent = new Intent(context, AddGiftsActivity.class);
                context.startActivity(intent);
            }
        });

        TabPagerAdapter adapter = new TabPagerAdapter(this, getSupportFragmentManager());
        final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                animateFab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//
//        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                // do your work
//            }
//        });
    }

    private void animateFab(int position) {
        switch (position) {
            case 0:
                fab.show();
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Context context = view.getContext();
                        Intent intent = new Intent(context, AddGiftsActivity.class);
                        context.startActivity(intent);
                    }
                });
                break;
            case 1:
                fab.show();
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Context context = view.getContext();
                        Intent intent = new Intent(context, AddGiftsActivity.class);
                        context.startActivity(intent);
                    }
                });
                break;

            default:
                fab.hide();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
            case R.id.action_settings:
                return true;
            case R.id.action_logout:
                facebookLogout();
        }

        return super.onOptionsItemSelected(item);
    }

    static class TabPagerAdapter extends FragmentStatePagerAdapter {

        private Context mContext;

        public TabPagerAdapter(Context context, FragmentManager fm) {
            super(fm);
            mContext = context;
        }

        public Fragment getItem(int position) {
            if (position == 0) {
                return new MyGiftsFragment();
            } else if (position == 1) {
                return new FriendsGiftsFragment();
            } else {
                return new AboutMeFragment();
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            if (position == 0) {
                return mContext.getString(R.string.my_gifts);
            } else if (position == 1) {
                return mContext.getString(R.string.friends_gifts);
            } else {
                return mContext.getString(R.string.about_me);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void facebookLogout() {
        if (mAuth.getCurrentUser() != null) {
            Log.e("22", "Not sign out yet.");
        } else {
            Log.e("22", "Signed out already.");
        }
        mAuth.signOut();
        if (mAuth.getCurrentUser() != null) {
            Log.e("22", "Not sign out yet.");
        } else {
            Log.e("22", "Signed out already.");
        }
        LoginManager.getInstance().logOut();
        Log.e("facebook", "logout");
        startActivity(new Intent(MainScreenActivity.this, FacebookLoginActivity.class));
        finish();
    }
}

这是MyGiftsFragment

public class MyGiftsFragment extends Fragment {

    private static final String TAG = MyGiftsFragment.class.getName();
    private ArrayList<Gift> mGiftArray;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private DatabaseReference mDatabase;
    private String facebookId;

    public MyGiftsFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {



        View rootView =  inflater.inflate(R.layout.fragment_list_view, container, false);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mGiftArray = new ArrayList<>();

        SharedPreferences mSharedPreferences = this.getActivity().getSharedPreferences("test", Activity.MODE_PRIVATE);
        facebookId = mSharedPreferences.getString("facebookId", "");


        mDatabase = FirebaseDatabase.getInstance().getReference();
        DatabaseReference myWishList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/wish_list");
        myWishList.addChildEventListener(new ChildEventListener() {
            /** Add new gift */
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                mGiftArray.clear();
                /** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
                final String uniqueKey = dataSnapshot.getKey();
                Log.e(TAG, "onChildAdded:" + uniqueKey);
                /** com.jluo80.amazinggifter.MyGiftsFragment:true */
                Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());

                DatabaseReference ref = mDatabase.child("gift").child(uniqueKey);
                ref.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot item) {

                        Log.e(TAG, "Single" + item.getKey());
                        System.out.println("test" + item.getValue());
                        Gift gift = item.getValue(Gift.class);
                        gift.setUnique_key(uniqueKey);
                        System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());

                        String end = gift.getDue_date();
                        String start = getCurrentDate();
                        if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
                            mGiftArray.add(gift);
                            mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                    }
                });
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "postComments:onCancelled", databaseError.toException());

            }
        });


        DatabaseReference fromFriendsList = mDatabase.child("user/" + facebookId + "/my_gift/" + "/from_friends");
        fromFriendsList.addChildEventListener(new ChildEventListener() {
            /** Add new gift */
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//                mGiftArray.clear();
                /** com.jluo80.amazinggifter.MyGiftsFragment:-KMa77KnGU5hsF8dngVc*/
                final String uniqueKey = dataSnapshot.getKey();
                Log.e(TAG, "onChildAdded:" + uniqueKey);
                /** com.jluo80.amazinggifter.MyGiftsFragment:true */
                Log.e(TAG, "onChildAdded:" + dataSnapshot.getValue());

                DatabaseReference ref = mDatabase.child("gift/" + uniqueKey);
                ref.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot item) {

                        Log.e(TAG, "Single" + item.getKey());
                        System.out.println("test" + item.getValue());
                        Gift gift = item.getValue(Gift.class);
                        gift.setUnique_key(uniqueKey);
                        System.out.println(gift.getInitiator_id() + "&&&&&&&" + gift.getReceiver_id());

                        String end = gift.getDue_date();
                        String start = getCurrentDate();
                        if(gift.getProgress() <= gift.getPrice() && end.compareTo(start) >= 0) {
                            mGiftArray.add(gift);
                            mRecyclerView.setAdapter(new MyGiftRecyclerAdapter(getContext(), mGiftArray));
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                    }
                });
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.e(TAG, "onChildChanged:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.e(TAG, "onChildRemoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.w(TAG, "postComments:onCancelled", databaseError.toException());

            }
        });
        return rootView;
    }

    public String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat mdformat = new SimpleDateFormat("MM/dd/yy");
        return mdformat.format(calendar.getTime());
    }
}

1 个答案:

答案 0 :(得分:1)

请在设置适配器之前添加此行。这将解决问题

viewPager.setOffscreenPageLimit(3);

屏幕外页面限制将决定在您看到页面时需要加载多少个相邻页面。因此在您的情况下将其设置为3(所有页面)。

然后您的代码将更改为,

final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);  //Add this
viewPager.setCurrentItem(0);
祝你好运!