totten
totten

Reputation: 2817

Android inline listener with final variables

Here's what I am doing,

final ObjType myObject = getObject...();
getView().findViewById(R.id.button_get).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        //do something with myObject.
        //...
        //do some other things with myObject.
        //...
        //OMG! this listener is getting long!
        //...
        //ahhgg.. this is the 2398 lines listener :/
    }
}

As you see from comments, my problem is, my listeners is getting too long and there is enormous count of listeners in my code.

This yields me to do some refactor about that. However, since I'm using final variable inside this anonymous listener class, I cannot split this class from my base class.

How can I achieve that?

Upvotes: 0

Views: 655

Answers (2)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You can factor out your ObjType related code out of your click handler into another class like ObjTypeClickHandler.

class ObjTypeClickHandler {

    public void onClick(View v, ObjType myObject) {
       // do some things with myObject.
    }
}

And then simply invoke the handler from the listener as

final ObjType myObject = getObject...();
getView().findViewById(R.id.button_get).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
       // ...
       new ObjTypeClickHandler().onClick(view, myObject);
       // ...
    }
});

So, if your close to 2500 lines of code is working with different objects, you can break your code into and delegate click processing to multiple such click handlers.

Upvotes: 1

Kevin Coppock
Kevin Coppock

Reputation: 134684

Break out your logic into a simple class that implements the OnClickListener interface, takes in ObjType as a parameter, then operates on that instance.

private static class ObjTypeClickListener implements View.OnClickListener() {
    private final ObjType mObject;

    ObjTypeClickListener(ObjType object) {
        mObject = object;
    }

    @Override
    public void onClick(View v) {
        // Do stuff with mObject
    }
}

Then, just set a new instance of this class as the listener:

getView().findViewById(R.id.button_get)
    .setOnClickListener(new ObjTypeClickListener(myObject));

Upvotes: 2

Related Questions