首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FragmentStatePagerAdapter - getItem

FragmentStatePagerAdapter - getItem
EN

Stack Overflow用户
提问于 2016-07-11 22:10:58
回答 2查看 2.8K关注 0票数 2

我知道还有其他几篇关于这个主题的文章,但是我想粘贴我的代码,因为我相信其中可能有一个错误导致了我的问题。我的FragmentStatePagerAdapter正在返回错误的位置,我不知道为什么。

这是我主要活动中的代码。

Main.java

代码语言:javascript
复制
 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);
            }
        }

    }

...and这里是我的FragmentStatePagerAdapter的代码

TabGroupAdapter

代码语言:javascript
复制
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时,它不会记录。挺奇怪的。另外,我在片段中的反箭头,只有当我不在选项卡的根段时才会出现,而是始终显示出来。

有人能帮我弄清楚为什么会发生这种事吗?如果需要更多的代码来确定问题,我很乐意发布它,请让我知道你需要看到什么。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-11 23:14:56

试着注释掉以下所有代码:

代码语言:javascript
复制
 TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

在您的onCreate方法中。再跑一次看看会发生什么。

您的开关语句也是以一种奇怪的方式排列的。如果您肯定只有5种情况,那么它应该从案例0到4,在最后是一个默认的大小写,将一个错误打印到日志中,或者抛出一个异常。我不认为这会引起你的问题,但这是很好的做法。

而且,使用默认构造函数实例化片段通常不是一个好主意。更好的方法是使用静态工厂方法,即:

代码语言:javascript
复制
Tab1Fragment fragment = Tab1Fragment.create();
return fragment;

使用片段中的静态create()方法初始化对象。它为您提供了一个单一的访问点到片段,并意味着您需要做的任何初始化(现在或在线上的某个点)都可以一次性完成,使您不太容易出错。Android还使用默认构造函数重新创建片段,因此在重载构造函数中进行的任何初始化都将被忽略。再说一次,我不认为这是你的问题的原因,但这是值得记住的。

编辑:此外,当你说它选择随机片段时,“位置将显示0,3,2,0,4,1只是随机数”,你的意思是那些是显示在屏幕上的片段,还是从"getItem(int位置)“参数中记录的位置?

票数 1
EN

Stack Overflow用户

发布于 2016-07-12 06:12:31

代码语言:javascript
复制
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);

然后在你的适配器

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38317017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档