我試圖讓一個活動啓動時選擇一個特定的選項卡,但是當我從該活動返回時,我希望以前顯示,而不是我單擊的選項卡。就像當你點擊Instagram上的加號按鈕一樣。ViewPager - 從setOnTabSelectedListener發起活動
像這樣:
默認片段1 /製表1
進入到碎片5 /製表5
點擊選項卡3,活動彈出
圍棋返回,參見片段5 /表5
現在,我將最後一次訪問的標籤索引存儲在一個變量中,然後當單擊標籤3時,它會轉到最後訪問的標籤。
tabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//super.onTabSelected(tab); -- Should keep this or leave it commented out?
int pos = tab.getPosition();
switch (pos) {
case 0:
viewPager.setCurrentItem(tab.getPosition(), false);
getSupportActionBar().setTitle("Home");
pre_pos = pos;
pre_title = "Home";
break;
case 1:
viewPager.setCurrentItem(tab.getPosition(), false);
getSupportActionBar().setTitle("Trending");
pre_pos = pos;
pre_title = "Trending";
break;
case 2:
viewPager.setCurrentItem(pre_pos, false);
getSupportActionBar().setTitle(pre_title);
Intent intent = new Intent(MainActivity.this, NewEvent_Activity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(),
"Curr: "+ viewPager.getCurrentItem()+
" Prev: " + pre_pos +
" Clicked: " +tab.getPosition(),
Toast.LENGTH_SHORT).show();
break;
case 3:
viewPager.setCurrentItem(tab.getPosition(), false);
getSupportActionBar().setTitle("Notifications");
pre_pos = pos;
pre_title = "Notifications";
break;
case 4:
viewPager.setCurrentItem(tab.getPosition(), false);
getSupportActionBar().setTitle("Profile");
pre_pos = pos;
pre_title = "Profile";
break;
}
}
});
在ViwPager.java
當setCurrentItem()
被稱爲
void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
if (mAdapter == null || mAdapter.getCount() <= 0) {
setScrollingCacheEnabled(false);
return;
}
//I think my problem lies in the following line (mCurItem == item)
if (!always && mCurItem == item && mItems.size() != 0) {
setScrollingCacheEnabled(false);
return;
}
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
item = mAdapter.getCount() - 1;
}
final int pageLimit = mOffscreenPageLimit;
if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
// We are doing a jump by more than one page. To avoid
// glitches, we want to keep all current pages in the view
// until the scroll ends.
for (int i = 0; i < mItems.size(); i++) {
mItems.get(i).scrolling = true;
}
}
final boolean dispatchSelected = mCurItem != item;
if (mFirstLayout) {
// We don't have any idea how big we are yet and shouldn't have any pages either.
// Just set things up and let the pending layout handle things.
mCurItem = item;
if (dispatchSelected) {
dispatchOnPageSelected(item);
}
requestLayout();
} else {
populate(item);
scrollToItem(item, smoothScroll, velocity, dispatchSelected);
}
}
我覺得這是我的問題,但我不能編輯它,它調用此函數。 有什麼建議嗎?
謝謝。
onResume()也會調用,當你第一次啓動你的Activity時,它會顯示默認的最後存儲的索引。 –