Harmony Valley
Harmony Valley

Reputation: 145

how to change layoutinflater to use another layout in kotlin to use fragments?

I'm improving an app by adding tabs (fragments), so now, my activity_main.xml is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">

<com.google.android.material.tabs.TabLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:backgroundTint="@color/purple_500"
    app:tabTextColor="@color/white"
    app:tabIndicatorColor="@color/white"
    android:id="@+id/tab_layout">

    <com.google.android.material.tabs.TabItem
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Home"/>
    <com.google.android.material.tabs.TabItem
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Notification"/>

    <com.google.android.material.tabs.TabItem
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Settings"/>


</com.google.android.material.tabs.TabLayout>

<androidx.viewpager2.widget.ViewPager2
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/view_pager"
    android:background="@color/teal_200"
    android:layout_below="@id/tab_layout"/>

and my home_fragment.xml has all the buttons, texts and so on that were on the activity_main.xml in the previous version of my app.

My problem is that I need to edit this line in the MainActivity.kt to use my home_fragment.xml:

private val binding by lazy {
    ActivityMainBinding.inflate(layoutInflater)
}

because in MainActivity.kt I have things like:

binding.shareUrl.visibility = View.VISIBLE

That points towards an element that has android:id="@+id/shareUrl" and now it is in the fragment_home.xml (before it works, because this element was in main_activity.xml

How do I solve this?

Upvotes: 0

Views: 98

Answers (1)

Ajay Chandran
Ajay Chandran

Reputation: 264

Try using Navigation Component for your case. Add a NavHostFragment in your activity_main file. Add navgraph and connect it to your host. Check this for more details.

https://appdevassist.com/android/android-tablayout-viewpager2-navgraph

Upvotes: 0

Related Questions