How to use view-binding library in extended classes

Viewed 423

I have an Android Project with 2 modules. I have MainActivity in both modules:

  • com.example.MainActivity
  • com.example.paid.PaidMainActivity

Both modules have res/layout/main.xml and they differ a bit.

Free version:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Paid version:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/paidView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

PaidMainActivity extends MainActivity and layout is set with setContentView in the parent activity. At the moment 90% of the functionality is same and is done in MainActivity.

public class MainActivity {
    TextView text1;
    TextView paidView;
    public void onCreate() {
       text1 = findViewById(R.id.text1);
       paidView = findViewById(R.id.paidView);
    }
    public void onResume() {
        text1.setText("This is just a text");
        if (paidView != null) {
            paidView.setText("All features unlocked");
        }
    }
}

ViewBinding generates two MainBinding java classes that I could use in either class but then I would have to refactor a lot of code (this sample is oversimplified). I would also have duplicate code in both Activities because I can't use the same binding object and override some functionality. Is there a way I can use view binding and a merged xml file with all the (@Nullable) views?

0 Answers
Related