Java – includeHow to use the Onclick event when using tags

How to use the Onclick event when using tags… here is a solution to the problem.

How to use the Onclick event when using tags

I have two java classes and two layouts for two classes.
There is a button in each layout.
Both classes extend Activities.
Now in the first layout I used an include tag like this

<include 
    android:id="@+id/clicked" 
    layout="@layout/activity_main" />

I can see two buttons now, but the second button doesn’t work.

Solution

First you must declare and initialize the include View, and then decalre and initialize both buttons using the view.findViewById() method, as follows:

View includeView = (View)findViewById(R.id.clicked);
Button button1 = (Button)includeView.findViewById(R.id.button1ID); decalre button like this
Button button2 = (Button)includeView.findViewById(R.id.button2ID);

Then set their onClickListeners

button1.setOnClickListener(new OnClickListener() {

@Override
            public void onClick(View v) {
                code whatever you want to do here
            }
        });

button2.setOnClickListener(new OnClickListener() {

@Override
            public void onClick(View v) {
                code whatever you want to do here
            }
        });

Edit

Fixed spelling errors. Should be includeView on findViewById.
Good explanation!

Related Problems and Solutions