8
votes

I want to create a fragment with ViewBinding but my code not working. I read ViewBinding Documentation but my fragment not show. This is my code:

fragment_player.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Test fragment"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

layout_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
    android:id="@+id/fragment_player"
    class="com.test.plo.view.PlayerFragment"
    android:name="com.test.plo.view.PlayerFragment"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

PlayerFragment.java

 public class PlayerFragment extends Fragment {

   private FragmentPlayerBinding fragmentPlayerBinding;

   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

       fragmentPlayerBinding = FragmentPlayerBinding.inflate(inflater, container, false);
       View view = fragmentPlayerBinding.getRoot();
       return view;
   }

  @Override
  public void onDestroyView() {
      super.onDestroyView();
      fragmentPlayerBinding = null;
  }

}

Can anyone help me?

2
Hi checkout this post completely explaining view binding with activity| fragment |Recycler Views| customview Androidbites|ViewBindingChetan Gupta
The best way I see here is to wrap the fragment inside a FrameLayout.Sai

2 Answers

0
votes

Have you tried to put:

android {
    ...
    buildFeatures {
    viewBinding true
    }
}

in your app build.gradle?

0
votes

First of all, In your app level put the below lines of code

    android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 19
        targetSdkVersion 30
        versionCode 1          
        versionName "1.0"       
        multiDexEnabled true
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    testOptions {
        unitTests.returnDefaultValues = true
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    //Enable View Bindings to true
    buildFeatures {
        viewBinding = true
    }
}

Then add new fragment in your project by Right click "File" -> New -> Fragment -> select Blank Fragment(or any fragment you want). This will create your fragment class file along with an xml file associated with it.
I have created blank fragment with name "HomeFragment.kt", and the name of its xml file is "fragment_home.xml".

In My xml file, I have added one textview and Button(you can define your widgets here-a design layout), And code will look like below.

"fragment_home.xml"

    <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    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">



  <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


                <com.google.android.material.textview.MaterialTextView
                    android:id="@+id/mTv_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Home Fragment"
                    android:textColor="@color/main_black"
                    android:lineSpacingExtra="@dimen/dimen_2dp"
                    android:gravity="center" />


 <com.google.android.material.button.MaterialButton
                    android:id="@+id/mBtn_homeButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Click Here!"
                    android:layout_gravity="center"
                    android:textSize="@dimen/dimen_20sp"
                    android:textAllCaps="false"
                    app:cornerRadius="@dimen/dimen_50dp"
                    android:paddingLeft="@dimen/dimen_50dp"
                    android:paddingRight="@dimen/dimen_50dp"
                    android:paddingTop="12dp"
                    android:paddingBottom="12dp" />

  </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

And finally in your fragment class, You can bind these attributes using viewBinding. "HomeFragment.kt"

    class HomeFragment : Fragment() {

    private lateinit var homeViewModel: HomeViewModel
    // view binding will create an Class for your xml file, you can use it directly by this "FragmentHomeBinding" as my xml file name is "fragment_home.xml" 
 // create a variable of your xml binding class
    private lateinit var binding : FragmentHomeBinding 

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments!=null) {
            Log.i(tag, "onCreate: ")
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        //val root = inflater.inflate(R.layout.fragment_home, container, false)
        binding = FragmentHomeBinding.inflate(inflater, container, false)

        // observe your text change by using viewModel
        homeViewModel.text.observe(viewLifecycleOwner, Observer {
            //you can use your view/widgets by using the binding object like this --- 
            binding.mTvTitle.text = it
        })

       // button click event -- using viewBinding 
       binding.mBtnHomeButton.setOnClickListener {
            Toast.makeText(context, "Hello..!", Toast.LENGTH_SHORT).show()
        }
       

        return binding.root
    }
}

Cheers..!