1

我知道這個主題有幾個其他帖子,但我想粘貼我的代碼,因爲我相信它可能會導致我的問題的錯誤。我的FragmentStatePagerAdapter返回錯誤的位置,我不知道爲什麼。FragmentStatePagerAdapter - getItem

這是我主要活動中的代碼。

Main.java

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

TabGroupAdapter

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語句,在該方法中我將當前位置記錄到控制檯。當我的應用程序加載它顯示位置:0,然後位置:1全部加載,這是奇怪的,因爲它應該只顯示位置0,因爲這是默認選項卡(tab1)。然後,當我點擊時,標籤2顯示位置2,標籤3顯示位置3,標籤4顯示位置4,標籤5根本不記錄。然後從第5個標籤恢復到第1個標籤,這些位置都沒有問題,當我到達第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)」參數記錄的位置?

+0

感謝您的見解。我註釋了上面提到的代碼下面的代碼,但仍然存在相同的問題。當我在隨機片段上表示位置是來自getItem方法的Log I調用。我有一個Log.d(「Mytag」,「位置:」+位置);從getItem方法中。當我的應用程序加載時,它會記錄「位置:0」,然後位置:1全部加載。然後當我點擊標籤2時,它表示位置:2,標籤3表示位置:3,標籤4表示位置:4和標籤5根本不記錄。那麼當我從第5個標籤回到第1個標籤時,這個序列全部都不起作用 – Phil

+0

我使用您在此處發佈的代碼構建了一個虛擬項目,並且所有內容都按照原樣運行。 FragmentStatePager適配器將加載當前頁面,並在任一側加載一頁。這就是爲什麼它同時記錄0和1。當您切換到第2頁時,它將加載第3頁並將第1頁保存在內存中。然後當你到達第4頁時,它不會加載任何東西,因爲當你滾動到3時加載了4,除此之外沒有任何東西。因此,getItem()中給出的int不是當前正在查看的頁面,而是正在加載到內存中的頁面。希望能爲你解決問題。 – Dan

+0

謝謝丹。您的評論幫助我意識到我的問題不在於返回的位置,而是問題在於我加載的片段。 – Phil

0
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); 
     } 
    } 
+0

你的getPageTitle方法返回一個片段而不是一個 CharSequence – Phil

相關問題