Aawesh Man Shrestha
Aawesh Man Shrestha

Reputation: 11

Using a single fragment with multiple layout in Android

I want to use a single fragment(Only Single Fragment Class that can laod multiple layout) with multiple layout. I have two layout xml files. According to the situation in the run time, i have to switch between the layout xml file. Actually the app has to post a form. If user has to fill the form, a fragment with questionnaire layout must be visible and when the user clicks the submit button, another layout within same fragment must be visible, displaying the results. And if a user has already submitted the form, a fragment with result layout must be visible.

Is it possible? If not please suggest any other feasible alternative.

Upvotes: 1

Views: 4770

Answers (1)

Niko
Niko

Reputation: 8153

One solution is that you can have simple FrameLayout for the Fragment view. Then use LayoutInflater to inflate corresponding view and add it to the FrameLayout. You can switch the layout by removing the existing view and inflate other to replace it.

Code would be something like this:

private FrameLayout mContainer;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    mContainer = (FrameLayout) inflater.inflate(R.layout.fragment_framelayout, null);

    onSubmittedStateChanged(SubmittedState.SUBMITTED); // OR SubmittedState.NOT_SUBMITTED

    return mContainer;
}

public void onSubmittedStateChanged(SubmittedState state) {
    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mContainer.removeAllViews();

    switch (state) {
    case SubmittedState.SUBMITTED:
        inflater.inflate(R.layout.submitted, mContainer);
        break;
    case SubmittedState.NOT_SUBMITTED:
        inflater.inflate(R.layout.not_submitted, mContainer);
        break;
    }
}

Upvotes: 1

Related Questions