实现底部导航栏及切换tab重新加载的问题解决-创新互联

许多的App都使用底部导航栏来实现导航功能,我们可以使用RadioGroup+RadioButton的形式或者直接Button数组的方式实现,而谷歌官方提供了FragmentTabHost来方便快捷实现底部导航栏。

站在用户的角度思考问题,与客户深入沟通,找到伊春网站设计与伊春网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计、做网站、企业官网、英文网站、手机端网站、网站推广、国际域名空间、网站空间、企业邮箱。业务覆盖伊春地区。

android.support.v4.app.FragmentTabHost

实现底部导航栏及切换tab重新加载的问题解决

主要代码:

fragmentTabHost.setup(this, getSupportFragmentManager(), R.id.layout_content);

for (int i = 0; i < TAB_NUM; i++){
    TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(mTitles[i]);
    tabSpec.setIndicator(getTabView(i));
    fragmentTabHost.addTab(tabSpec, mFragments[i], null);
}

布局文件:



    

    

    

    

实现代码:

public class FragmentTabHostActivity extends AppCompatActivity {

    private static final int TAB_NUM = 4;

    private Class[] mFragments = new Class[]{//tab对应的Fragment
            AFragment.class,
            BFragment.class,
            CFragment.class,
            DFragment.class
    };

    private int[] mTabDrawables = new int[]{//tab图片
            R.drawable.tab_work,
            R.drawable.tab_im,
            R.drawable.tab_ebook,
            R.drawable.tab_me,
    };

    private String[] mTitles = new String[]{//tab标题文字
            "工作",
            "微信",
            "通信录",
            "我的"
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tab_host);

        FragmentTabHost fragmentTabHost = (FragmentTabHost) findViewById(R.id.tabhost);
        fragmentTabHost.setup(this, getSupportFragmentManager(), R.id.layout_content);

        for (int i = 0; i < TAB_NUM; i++){
            TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(mTitles[i]);
            tabSpec.setIndicator(getTabView(i));
            fragmentTabHost.addTab(tabSpec, mFragments[i], null);
        }
        //部分机型可能会显示tab之间的分割线,设置为null取消掉
        fragmentTabHost.getTabWidget().setDividerDrawable(null);
    }

    private View getTabView(int index) {
        View view = View.inflate(this, R.layout.tab_indicator, null);
        ImageView iv = (ImageView) view.findViewById(R.id.maintab_iv);
        TextView tv = (TextView) view.findViewById(R.id.maintab_tv);

        iv.setImageDrawable(getDrawable(mTabDrawables[index]));
        tv.setText(mTitles[index]);

        return view;
    }
}

备注:

 这个实现方式有一个弊端,就是每次切换tab都会重新加载Fragment。实际项目过程种可能并不需要,而是需要在切换过程中保留Fragment状态。

原因:

 FragmentTabHost在切换tab的时候使用detach和attach的方法来显示/隐藏Fragment。

解决方法:

 修改FragmentTabHost的源代码将doTabChanged方法中的

 ft.detach(mLastTab.fragment); 改成  ft.hide(mLastTab.fragment);

 ft.attach(newTab.fragment); 改成 ft.show(newTab.fragment);

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站栏目:实现底部导航栏及切换tab重新加载的问题解决-创新互联
标题来源:http://pwwzsj.com/article/dphgcg.html