Java – Programmatically set up onClick listeners for buttons in a scene

Programmatically set up onClick listeners for buttons in a scene… here is a solution to the problem.

Programmatically set up onClick listeners for buttons in a scene

I have 2 layouts with the same button

layout_1.xml

  <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button_1"
        android:text="button2"
        android:background="@android:color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </RelativeLayout>

And.
layout_2.xml

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button_1"
        android:text="button2"
        android:background="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </RelativeLayout>

Please assume these are valid layouts etc. (I’m just adding the relevant code.) )。

So in my fragment, I bloat and use layout_1.xml in onCreateView. I want to use button_1 to switch between two scenes.
I can set up listeners for button_1 in layout_1.xml during onCreateView().
The problem is trying to set up a listener on that button in the second View. That is, the listener will not activate for the second scene (using layout_2.xml). So I can’t switch between the two scenes. Is there a way to achieve this?

Solution

In fact, the correct way to do this is to define the action to be performed in the second scenario:

mSecondScene.setEnterAction(new Runnable() {
        @Override
        public void run() {
                 ((Button) mSecondScene.getSceneRoot().findViewById(R.id. button_1)).setOnClickListener( ... );
    }

This will allow you to set up a ClickListener on the View without bindging data to a generic click listener method. Then you can perform the transition to the second scene and viola.

Related Problems and Solutions