1

MainActivity shows a viewpager so there are 3 layout files:activity_main.xml、card1.xml and card2.xml Now I want to get view from card1.xml and set the listener. what should I do?

I tried using this:

LayoutInflater layout=this.getLayoutInflater();
View view=layout.inflate(R.layout.card1, null);
Button b=(Button)view.findViewById(R.id.b);

then set OnClickListener:

b.setOnClickListener(new MyClickListener(0));

but useless.

Elva
  • 176
  • 9

2 Answers2

3

In your card1.xml, you can add a onClick attribute, and just provide the method name as the attribute's value, like this:

<Button android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myMethod" />

Now in you MainActivity.java file, create a public method with return type as void, and which takes in a View parameter, like this:

    public void myMethod(View v) {  
    // do your thing here  
    }

You can read more about it here.

Community
  • 1
  • 1
Eric B.
  • 4,622
  • 2
  • 18
  • 33
0
public class MyClickListener implements OnClickListener {

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.your_btn_id:
            // your code 

            break;


        }

    }

}

another way is you can add button click listener in your card1.xml fragment class.

Salauddin Gazi
  • 1,497
  • 1
  • 13
  • 18