Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method defined in another activity/class onClick() of a Button ellement?

I am working on the Layout of my main activity with Android Studio (lowest API is 15), and have defined a few XML Buttons on it.

The idea of the program is to edit a list of words by adding to, displaying, and clearing it with a set of buttons. (There is an EditText for adding, but that's not important for the question). But with the idea of high cohesion in mind, I have defined this list and the methods that manipulate it in another plain class called WordList (which still extends Activity), and so when trying to invoke the onClick property of a button, it cannot find them.

android:onClick="addWord"

Method 'addWord' is missing in 'MainActivity' or has incorrect signature...

Is there a way to make the layout, or the individual element point (or get its data context) from another class, or is that against the whole structure of Android and I should just put it in its original activity?

like image 745
Derptastic Avatar asked Jan 28 '16 21:01

Derptastic


People also ask

How do you access a method from another activity?

The Best Answer is You can use startActivityForResult or you can pass the values from one activity to another using intents and do what is required. But it depends on what you intend to do in the method.

Which method is used to handle event on a button when a button is clicked?

When the user clicks a button, the Button object receives an on-click event. To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

What are the two ways of defining a click event for a button?

There are two ways to do this event handler programmatically : Implementing View. OnClickListener in your Activity or fragment. Creating new anonymous View.


1 Answers

Are you using the correct signature for the method?

Methods defines using the onClick attribute must meet the following requirements:

  • must be public
  • must have a void return value
  • must have a View object as parameter (which is the view that was clicked)

like

public void addWord(View view) {
    //your action
}
like image 130
TeChNo_DeViL Avatar answered Nov 08 '22 04:11

TeChNo_DeViL