How to show different layouts in each Tab in a TabLayout using Fragments

不羁岁月 提交于 2019-12-04 16:25:20
 View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        switch (getArguments().getInt(ARG_SECTION_NUMBER))
        {
            case 1: {
                rootView = inflater.inflate(R.layout.fragment_bba, container, false);
                break;
            }
            case 2: {
                rootView = inflater.inflate(R.layout.fragment_bcom, container, false);
                break;
            }

            case 3: {
                rootView = inflater.inflate(R.layout.fragment_bca, container, false);
                break;
            }

        }
        return rootView;

Ok for the people who want to solve this problem using design patterns.
Find full working solution Here.

If u write the fragment based on if-else condition it may solve the problem

switch(fragmentId)
    {
    case 1:
    {
      fragment 1 related stuff
    }
    case 2:
    {
    fragment 2 related stuff
    }
    .......
    .......
    and so on

But the problem with this approach is if in future,

1) you decide to add more fragments

or

2) you decide to change some functionality of existing fragment

Then you will have to modify the existing code (inside if-else condition)
Not a preferred programming practice

Instead you can follow this approach

public abstract class BasicFragment extends Fragment {

public BasicFragment newInstance()
{
    Log.d("Rohit", "new Instance");
    Bundle args = new Bundle();
   // args.putInt(ARG_PAGE, page);
    BasicFragment fragment = provideYourFragment();
    fragment.setArguments(args);
    return fragment;

}

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
}

public View onCreateView(LayoutInflater inflater,ViewGroup parent, Bundle savedInstanseState)
{
    View view = provideYourFragmentView(inflater,parent,savedInstanseState);
    return view;
}

public abstract BasicFragment provideYourFragment();

public abstract View provideYourFragmentView(LayoutInflater inflater,ViewGroup parent, Bundle savedInstanceState);
}

Your Fragment implementation

public class ImageFragment extends BasicFragment{
@Override
public BasicFragment provideYourFragment() {

    return new ImageFragment();
}

@Override
public View provideYourFragmentView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.image_fragment,parent,false);

    //Get your parent layout of fragment
    RelativeLayout layout = (RelativeLayout)view;

    //Now specific components here

    ImageView imageView = (ImageView)layout.findViewById(R.id.myImage);
    imageView.setImageResource(android.R.drawable.ic_media_play);

    return view;

}
}

Happy coding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!