Search code examples
androidandroid-tabbed-activity

How to show Views of inflated layout in Tabbed Activity?


I made a default tabbed activity in android studio. and I tried to show 2 views using tab1 and tab2. They inherit LinearLayout. Following is their code(Tab1).

public class Tab1 extends LinearLayout {
    View rootView;

    public Tab1(Context context) {
        super(context);
        init(context);
    }

    public Tab1(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    //inflater
    private void init(Context context) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        rootView = inflater.inflate(R.layout.fragment_main_tab1, this, true);
    }

    public View getView(){ //getter
        return rootView;
    }
}

Here is onCreateView method I made in default tabbed activity. I wanted to show tab1, tab2 at each tabs.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView; //return view
    Tab1 tab1 = new Tab1(StaticManager.applicationContext); //inflated activity
    Tab2 tab2 = new Tab2(StaticManager.applicationContext); //inflated activity

    if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
        container.addView(tab1);
        rootView = tab1.getRootView();
    } else {
        container.addView(tab2);
        rootView = tab2.getRootView();
    }
    return rootView;
}

and error message is this,

05-06 14:36:57.972 19264-19264/kr.eyeballs.mobilecloudchattingapp E/AndroidRuntime: FATAL EXCEPTION: main
05-06 14:36:57.972 19264-19264/kr.eyeballs.mobilecloudchattingapp E/AndroidRuntime: Process: kr.eyeballs.mobilecloudchattingapp, PID: 19264
05-06 14:36:57.972 19264-19264/kr.eyeballs.mobilecloudchattingapp E/AndroidRuntime: java.lang.StackOverflowError

It dosen't work. How should i fix this?

If you don't understand what i mean, let me know will add more information.


Solution

  • you called the wrong method, you should call getView() instead of getRootView() in your fragment. The peace of code in ViewGroup cause the stackoverflow:

       /**
         * @hide
         */
        @Override
        public void resetResolvedLayoutDirection() {
            super.resetResolvedLayoutDirection();
    
            int count = getChildCount();
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.isLayoutDirectionInherited()) {
                    child.resetResolvedLayoutDirection();
                }
            }
        }