Home > Software design >  Android Studio (API 23) - I want to reuse a fragment across multiple activities, but with a unique l
Android Studio (API 23) - I want to reuse a fragment across multiple activities, but with a unique l

Time:03-02

Is this possible?

Essentially -

I want ActivityA to host FragmentA with layoutA, and I want ActivityB to host FragmentA with layoutB. I can't seem to figure out a way to do it conveniently.

Thank you!

Sorry - I don't have any example code handy that's worth looking at!

CodePudding user response:

I don't see a point for 2 layouts in same fragment file because binding the views and handle it will be big .. yes you can render different layouts depending on any flag you pass to fragment like this

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    val flag = requireArguments().getInt("AnyCustomFlag", 0)
    return if (flag == 1)
        inflater.inflate(R.layout.layout_a, container, false)
    else
        inflater.inflate(R.layout.layout_b, container, false)
}

CodePudding user response:

You can check the activity class inside the onCreateView and assign the good layout

  @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(getActivity() instanceof  ActivityA ? R.layout.fragment_a : R.layout.fragment_b, container, false); ;
    }
  • Related