How to connect button to main activity in Android studio?

6.4k views Asked by At

I think that my question is easy but I have no idea how to solve it.

I made a java class (test_class) and xml file for this class. In xml file I made a button and its work correctly in test_class, but I have to use it in MainActivity. I made this button public and made object of this class, but the button is null. I also tried to make button from main activity

Button btn = (Button) findViewById(R.id.logButton)

but its also null.

How can I solve this problem?

thanks in advance!

1

There are 1 answers

0
Maverick Meerkat On

In MainActivity.java make a public void method that takes a View parameter. e.g.

public void buttonPressed(View view) {
     // do stuff
}

In activity_main.xml - in your button node add

<Button
   ...
   android:onClick="buttonPressed"
   ...
/>

And now they're wired.