Android How to convert ViewStub code for ViewBinding?
Asked Answered
C

0

0

I have a RecyclerView project with a few ViewStubs. I am converting all of the findViewByIds for the project's xml layouts over to use ViewBinding.

How do I convert my existing code for ViewStubs? I did review this stackoverflow: How to inflate a ViewStub using ViewBinding in Android but the solution there was written in Kotlin.

Example of existing code is shown below.

MainActivity(prior):

    private ViewStub onboardingViewStub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (onboardingViewStub == null) {
            onboardingViewStub = findViewById(R.id.onboardingViewStub);
            onboardingViewStub.inflate();
            onboardingViewStub.setVisibility(View.VISIBLE);
        }
    }


activity_main.xml:

<androidx.coordinatorlayout.widget.CoordinatorLayout

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"  >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"  >
        ...
 
        <ViewStub
            android:id="@+id/onboardingViewStub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout="@layout/custom_stub2" />
    </RelativeLayout>

     
custom_stub2.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"  >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"    
        android:text="@string/onboarding_main_act"  />

</RelativeLayout>

MainActivity(new):

    private ActivityMainBinding binding8; 
    private CustomStub2Binding customStub2Binding; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        binding8 = ActivityMainBinding.inflate(getLayoutInflater());
        View view8 = binding8.getRoot();
        setContentView(view8);
    }
Cowper answered 11/2 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.