[英]FragmentStatePagerAdapter - getItem
我知道還有其他幾篇關於這個主題的帖子,但我想粘貼我的代碼,因為我相信其中可能有一個錯誤導致了我的問題。 我的 FragmentStatePagerAdapter 返回錯誤的位置,我不知道為什么。
這是我的主要活動中的代碼。
主程序
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.microsoft.windowsazure.notifications.NotificationsManager;
import java.util.ArrayList;
public class Main extends AppCompatActivity {
public static TextView txtViewHeading;
public static TextView tab1TabBadge;
public static TextView tab2TabBadge;
public static TextView tab3TabBadge;
public static TextView tab4TabBadge;
public static TextView tab5TabBadge;
public static Button btnBack;
public static ImageButton btnShare;
public static Main mainActivity;
public static Context mainActivityContext;
public static Boolean isVisible = false;
private FragmentTabHost mTabHost;
private GoogleCloudMessaging gcm;
private ActionBar actionBar;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private TabGroupAdapter mTabGroupAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set up Push notifications
mainActivity = this;
mainActivityContext = Main.this;
NotificationsManager.handleNotifications(this, NotificationSettings.SenderId, PushHandler.class);
registerWithNotificationHubs();
// Set up the views for each tab - custom view used for Badge icon
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Bind the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Set up the ActionBar
actionBar = getSupportActionBar();
if (actionBar!=null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
// Create the adapter that will return a fragment for each of the primary "tabs"
mTabGroupAdapter = new TabGroupAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mTabGroupAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
// tab1 Tab
View tab1TabView = inflater.inflate(R.layout.tab, null);
ImageView tab1TabIcon = (ImageView) tab1TabView.findViewById(R.id.tabIcon);
tab1TabIcon.setImageResource(R.drawable.tab_first);
TextView tab1TabText = (TextView) tab1TabView.findViewById(R.id.tabText);
tab1TabText.setText("tab1");
tab1TabText.setTypeface(arialTypeface);
tab1TabBadge = (TextView) tab1TabView.findViewById(R.id.tabBadge);
tab1TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(0).setCustomView(tab1TabView);
// Also set this tab as Active be default
tabLayout.getTabAt(0).getCustomView().setSelected(true);
mViewPager.setCurrentItem(0);
// tab2 Tab
View tab2TabView = inflater.inflate(R.layout.tab, null);
ImageView tab2TabIcon = (ImageView) tab2TabView.findViewById(R.id.tabIcon);
tab2TabIcon.setImageResource(R.drawable.tab_second);
TextView tab2TabText = (TextView) tab2TabView.findViewById(R.id.tabText);
tab2TabText.setText("Odometer");
tab2TabText.setTypeface(arialTypeface);
tab2TabBadge = (TextView) tab2TabView.findViewById(R.id.tabBadge);
tab2TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(1).setCustomView(tab2TabView);
// tab3 Tab
View tab3TabView = inflater.inflate(R.layout.tab, null);
ImageView tab3TabIcon = (ImageView) tab3TabView.findViewById(R.id.tabIcon);
tab3TabIcon.setImageResource(R.drawable.tab_third);
TextView tab3TabText = (TextView) tab3TabView.findViewById(R.id.tabText);
tab3TabText.setText("tab3");
tab3TabText.setTypeface(arialTypeface);
tab3TabBadge = (TextView) tab3TabView.findViewById(R.id.tabBadge);
tab3TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(2).setCustomView(tab3TabView);
// tab4 Tab
View tab4TabView = inflater.inflate(R.layout.tab, null);
ImageView tab4TabIcon = (ImageView) tab4TabView.findViewById(R.id.tabIcon);
tab4TabIcon.setImageResource(R.drawable.tab_fourth);
TextView tab4TabText = (TextView) tab4TabView.findViewById(R.id.tabText);
tab4TabText.setText("tab4");
tab4TabText.setTypeface(arialTypeface);
tab4TabBadge = (TextView) tab4TabView.findViewById(R.id.tabBadge);
tab4TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(3).setCustomView(tab4TabView);
// tab5 Tab
View tab5TabView = inflater.inflate(R.layout.tab, null);
ImageView tab5TabIcon = (ImageView) tab5TabView.findViewById(R.id.tabIcon);
tab5TabIcon.setImageResource(R.drawable.tab_fifth);
TextView tab5TabText = (TextView) tab5TabView.findViewById(R.id.tabText);
tab5TabText.setText("tab5");
tab5TabText.setTypeface(arialTypeface);
tab5TabBadge = (TextView) tab5TabView.findViewById(R.id.tabBadge);
tab5TabBadge.setTypeface(arialTypeface);
tabLayout.getTabAt(4).setCustomView(tab5TabView);
// Tab listener
/*
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
txtViewHeading.setText(tab.getText());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if(mViewPager.getCurrentItem()==0){
onBackPressed();
}
else{
mViewPager.setCurrentItem(mViewPager.getCurrentItem()-1);
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
isVisible = false;
}
@Override
protected void onResume() {
super.onResume();
isVisible = true;
}
@Override
protected void onStop() {
super.onStop();
isVisible = false;
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
ToastNotify("This device is not supported by Google Play Services.");
finish();
}
return false;
}
return true;
}
public void ToastNotify(final String notificationMessage) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(Main.this, notificationMessage, Toast.LENGTH_LONG).show();
}
});
}
private void registerWithNotificationHubs()
{
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
}
...這是我的 FragmentStatePagerAdapter 的代碼
選項卡組適配器
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import java.util.ArrayList;
public class TabGroupAdapter extends FragmentStatePagerAdapter {
private static int fragmentSize = 5;
private static ArrayList<String> fragmentTitles = new ArrayList<String>() {
{
add("tab1");
add("tab2");
add("tab3");
add("tab4");
add("tab5");
}
};
public TabGroupAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Log.d("tag","POSITION: " + position);
switch (position) {
case 0:
default:
return new Tab1Fragment();
case 1:
return new Tab2Fragment();
case 2:
return new Tab3Fragment();
case 3:
return new Tab4Fragment();
case 4:
return new Tab5Fragment();
}
}
@Override
public int getCount() {
return fragmentSize;
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTitles.get(position);
}
}
總而言之,當我的應用加載時,第一個選項卡是空的。 只是一個空白的屏幕。 它不是我的 Tab1Fragment 應該的樣子。 此外,當我單擊選項卡時,位置應從左到右顯示 0、1、2、3、4,因為我有 5 個選項卡。 但它沒有。 我的 getItem(position) 方法中有一個 Log.d 語句,我將當前位置記錄到控制台。 當我的應用程序加載時,它顯示 Position:0,然后 Position:1 全部加載,這很奇怪,因為它應該只顯示位置 0,因為這是默認選項卡 (tab1)。 然后當我點擊時,選項卡 2 顯示位置 2,選項卡 3 顯示位置 3,選項卡 4 顯示位置 4,選項卡 5 根本不記錄。 然后從選項卡 5 返回到選項卡 1,這些位置都失控了,當我到達選項卡 1 時,它不會記錄。 這很奇怪。 此外,我的片段中的后退箭頭應該只在我不在選項卡的根片段時顯示,而是一直顯示。
誰能幫我弄清楚為什么會這樣? 如果需要更多代碼來確定問題,我很樂意發布它,請讓我知道您需要查看什么。
嘗試注釋掉下面的所有代碼:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
在您的 onCreate 方法中。 再次運行,看看會發生什么。
你的 switch 語句也以一種奇怪的方式布局。 如果你肯定只有 5 個案例,那么它應該從案例 0-4 開始,最后有一個默認案例,將錯誤打印到日志,或拋出異常。 我不認為這會導致您的問題,但這是一種很好的做法。
此外,使用默認構造函數實例化片段通常不是一個好主意。 更好的方法是使用靜態工廠方法,即:
Tab1Fragment fragment = Tab1Fragment.create();
return fragment;
使用片段中的靜態 create() 方法來初始化對象。 它為您提供了一個片段訪問點,這意味着您需要進行的任何初始化(現在或在線下的某個時間點)都可以在一個地方完成,從而使您不易出錯。 Android 還使用默認構造函數重新創建片段,因此您在重載構造函數中進行的任何初始化都將被忽略。 同樣,我認為這不是您問題的原因,但值得牢記。
編輯:另外,當你說它選擇隨機片段“位置將顯示 0,3,2,0,4,1 只是隨機數”時,你的意思是那些是屏幕上顯示的片段,還是那些您從“getItem(int position)”參數記錄的位置?
viewPager = (ViewPager) findViewById(R.id.tabPager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(),"fragment 1");
adapter.addFragment(new Fragment2(),"fragment 2");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
return position;
}
}
@Override
public void onPageSelected(int position) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
assert tabLayout != null;
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
然后在你的適配器中
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment,String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.