Android Tabbed Activity: Action Bar Tabs with ViewPager: different layout for each tab

前端 未结 1 811
粉色の甜心
粉色の甜心 2021-01-07 12:09

I have a total blackout, I am not familiar to work with fragments.

I created with the eclipse assistant a new Android project:

相关标签:
1条回答
  • 2021-01-07 13:05

    You need to make different classes for each page. A page extends from a Fragment. You can just load a different layout-xml for every fragment.

    public class FirstFragment extends Fragment{
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    
    
        View rootView = inflater.inflate(R.layout.<yourxmlhere>, container,
                false);
        return rootView;
    }
    
    }
    

    You know have the fragment, but your adapter still needs to know which page (position) is which fragment. This is decided in the following function:

    @Override
    public Fragment getItem(int position) {
        switch (position){
        case 0:
        //page 1
        return new FirstFragment();
        break;
    
        case 1:
        //page 2
        return new SecondFragment();
        break;
        default:
        //this page does not exists
        return null;
    }
    

    Make sure you have set the correct amount of pages!

    @Override
    public int getCount() {
        //the amount of pages your adapter knows
        return <youramountofpages>;
    }
    

    This should get you up and running.

    EDIT: You can just delete the whole placeholderfragment class. It is not needed anymore.

    0 讨论(0)
提交回复
热议问题