2

I was planning on having two layout versions for the profile fragment, one for new user and one for logged in user.

How would I dynamically switch/choose the necessary layout in the Fragment's onCreateView() method?

The most straight-forward idea that comes to mind is to use two <include> layouts and hiding one of them in onCreateView() depending on variables. But I was wondering if there is a smarter approach.


Current layout xml:
The main content is inside the second FrameLayout and I'd like to have two versions to choose from.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.MainActivity">

    <ImageView
        android:id="@+id/profile_monk_head_imageview"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:contentDescription="@string/profile_monk_image_content_desc"
        android:src="@drawable/monk_head" />

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- This is what I want to switch out -->
        <FrameLayout ... >

    </androidx.core.widget.NestedScrollView>

</FrameLayout>
Big_Chair
  • 2,781
  • 3
  • 31
  • 58

1 Answers1

1

Use DataBindingUtil version inflate if layoutId is unknown in advance ( a.k.a dynamic binding). Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

enter image description here

Crosslink reference

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
  • This is to create the main layout of the fragment, right? But then how do I use the resulting binding object to swap content between layout A and B? – Big_Chair Nov 15 '20 at 17:44
  • 1
    Ohh, you mean I can have two completely separate layouts and then decide which one I want to inflate. But it seems a bit wasteful because the top containers are the same, so I would have redundant code. Is there a way to only change parts of the layout dynamically, like with switchig `` ? – Big_Chair Nov 15 '20 at 18:10
  • @Big_Chair just curious if you able to find a solution? – Tara Mar 03 '23 at 14:11
  • 1
    @Tara I tried splitting them up with `` and stuff, but in the end I just decided it's simpler to just have one layout and show/hide elements based on context (because the two layouts would have been so similar). https://stackoverflow.com/a/64858848/1972372 – Big_Chair Mar 03 '23 at 14:39
  • @Big_Chair my case is a bit different. I want to show same views but on different positions. Like i have to change constraints of the views at run time. Which is really tough programatically. I have 30 to 35 views. For this i want to use separate layouts. I am stuck right now. – Tara Mar 03 '23 at 15:41