user3507451
user3507451

Reputation: 39

How to use Onclick event when using <include> tag

I have two java class and two layout for both the class. Each layout is having one button in it. Both classes are extending Activity. Now in first layout I used include tag like this

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

I can now see two buttons but the second button is not working.

Upvotes: 3

Views: 4075

Answers (1)

Pankaj
Pankaj

Reputation: 8058

First You have to declare and initialise the include view and then decalre and initialise both buttons using 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);

And 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 the typo. Should be includeView on the findViewById. Good explanation though!

Upvotes: 5

Related Questions