如何在最新的Android设计支持库中将Tabs添加到TabLayout

时间:2015-08-09 14:38:58

标签: android android-support-library android-design-library android-tablayout

我是Android开发的新手。我按照教程http://slidenerd.com/2015/07/22/android-design-support-library/将相同的片段添加到tablayout.But我需要向tablayout添加3个独特的片段,从web服务器下载数据。如何进行编程???? 这是代码      `      包com.example.naveen.helloworld;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class AppMainScreen extends AppCompatActivity {
private Toolbar mToolbar;
private TabLayout mTablayout;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_main_screen2);
    mToolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(mToolbar);
    mTablayout = (TabLayout) findViewById(R.id.tab_layout);
    mViewPager = (ViewPager) findViewById(R.id.view_pager);
    mViewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
    mTablayout.setupWithViewPager(mViewPager);
}

class PagerAdapter extends FragmentStatePagerAdapter {
    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {
        Fragment fragment =null;
        switch (position) {
            case 0:                    return new Fragment();
            case 1:                    return new Fragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }

    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "News Feed";
            case 1:
                return "Events";
            default:
                return "News Feed";
        } }   }}`

提前完成。

1 个答案:

答案 0 :(得分:0)

寻呼机适配器内的getItem方法设置片段,只需将开关案例修改为

即可
switch(position){
   case 0: 
     return new NewsFragment();
   case 1: 
     return new EventsFragment();
}

NewsFragmentEventsFragment替换为您需要显示的相应片段