我知道关于该主题还有其他几篇文章,但是我想粘贴我的代码,因为我认为其中可能有错误导致我的问题。我的FragmentStatePagerAdapter返回错误的位置,我不确定为什么。
这是我的主要活动中的代码。
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时,它不会登录。真奇怪另外,片段中的后退箭头应该仅在我不在选项卡的根片段时才显示,而是一直显示。
谁能帮我弄清楚为什么会这样吗?
如果需要更多代码来确定问题,我很乐意将其发布,请告诉我您需要看什么。
最佳答案
尝试注释掉下面的所有代码:
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)”参数记录的位置?