7

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?

Derptastic
  • 491
  • 1
  • 6
  • 18

3 Answers3

13

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
}
TeChNo_DeViL
  • 739
  • 5
  • 11
4

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

https://stackoverflow.com/a/29479937/1496693

Community
  • 1
  • 1
airowe
  • 794
  • 2
  • 9
  • 29
  • @Derptastic No problem. I may have misunderstood your problem, but if you have an xml declared view that needs to call an onClick method in an activity where its parent layout wasn't inflated, it's best to use an onClickListener (I always listen for button clicks this way, but it's not necessary). – airowe Jan 28 '16 at 21:36
0

Try this, it should work:

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 Implementation

<?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 -->
Stanojkovic
  • 1,612
  • 1
  • 17
  • 24