Skip to content Skip to sidebar Skip to footer

Dynamically Include Another Layout In Fragment Activity

This is my Home.xml layout file Copy

Then you can retrieve the container in your Fragment like this:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.home, container, false);

    // Retrieve your container
    flContainer = rootView.findViewById(R.id.flContainer);

    b1 = (Button) rootView.findViewById(R.id.btn2);
    b1.setOnClickListener(this);

    return rootView;
}

And later when you want to add your layout you can add a child to the FrameLayout like this:

flContainer.addView(subLayout);

If you later want to change the layout in your container you can do it like this:

flContainer.removeAllViews();
flContainer.addView(otherLayout);

Solution 2:

Use LayoutParams.

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.BELOW, R.id.btn2);

r1.addView(layoutInflater.inflate(R.layout.test1, con , false),params);

Or put the view in your layout and toggle visibility with View.setVisibility(View.GONE/View.VISIBLE)

Post a Comment for "Dynamically Include Another Layout In Fragment Activity"