Cilenco
Cilenco

Reputation: 7117

Define onClick Method in other class

With xml I'm able to define an onClick method which is called if I click on the view:

android:onclick="onClick"
public void onClick(View v)

This method must be defined in the Activity class, which is visible. Now I have many controls with different onClick methods. This makes the Activity class very confusing, so is there a way to define this methods in an other class?

Of course I can use different classes or onClickListener in the class itself but with the xml it is so pretty easy. With onClickListeners comes some "unused code" because Java has no lamda expression at the moment and that makes it confusing, too. I think xml is a quick and clear method but not if you have so many methods like I have at the moment.

Upvotes: 2

Views: 2208

Answers (4)

marcinj
marcinj

Reputation: 49976

Looking into sources it looks like it must be a method that is in the class that extends Context class with which View was created:

http://androidxref.com/4.4_r1/xref/frameworks/base/core/java/android/view/View.java#3780

look into this line:

getContext().getClass().getMethod( ... )

reflection is being done on getContext()

You can do as other answers suggest, switch on view id, and call functions in other classes. Or if your app is complicated, maybe divide your layout into fragments?

Upvotes: 2

Sush
Sush

Reputation: 3874

make activity implement onclick listener and implement the method like below.

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    int key  = v.getId();
    switch (key) {
    case R.id.message_field:
            // handle click

        break;

    default:
        break;
    }
}

Upvotes: 0

Nathan Walters
Nathan Walters

Reputation: 4126

Anything onClick method defined in XML is called on the Activity that is hosting that layout. You could forward all incoming clicks to another class if you really want to do that, but the best way is either an OnClickListener or to use different onClick method names for each button.

Upvotes: 0

Pablo_Cassinerio
Pablo_Cassinerio

Reputation: 887

I'm not entirely sure about what you want, but you can just use different method names, it doesn't have to be "onClick"

Other than that, I believe they do have to be in that activity.

Upvotes: 0

Related Questions