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

I am working on a layout of my main activity with Android Studio (the lowest API is 15) and have defined several XML buttons on it.

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

android:onClick="addWord"

The 'addWord' method is missing from 'MainActivity' or has the wrong signature ...

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

+4
source share
3 answers

Are you using the correct signature for the method?

Methods that determine the use of an attribute onClickmust satisfy the following requirements:

  • must be publicly available.
  • should have a void return value
  • should have a View object as a parameter (which is the view viewed)

like

public void addWord(View view) {
    //your action
}
+10
source

Add an OnClickListener to the button instead of using the XML onClick attribute.

fooobar.com/questions/264163 / ...

+3

, :

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        addWord(v);
    }
});

// some more code

public void addWord(View v) {
    // does something very interesting
}

XML

<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click me!"
    android:onClick="addWord" />
<!-- even more layout elements -->
0
source

Source: https://habr.com/ru/post/1626442/


All Articles