Sibelius Seraphini
Sibelius Seraphini

Reputation: 5613

Android java class with a lot of Listeners Interfaces

Usually my Activity classes have to implements more than 2 interface, making my classes huge.

In Swift, you can handle this problem using extensions

class MyViewcontroller: UIViewController {
  // class stuff here
}

// MARK: - UITableViewDataSource
extension MyViewcontroller: UITableViewDataSource {
  // table view data source methods
}

// MARK: - UIScrollViewDelegate
extension MyViewcontroller: UIScrollViewDelegate {
  // scroll view delegate methods
}

How can I handle this in Java?

Upvotes: 0

Views: 71

Answers (2)

Sattar Hummatli
Sattar Hummatli

Reputation: 1408

Create Interface with some count of functions and other Adapter calss wich implements it with empty body.

Then include that adapter instead of listener and overide method.

This is java language standart

For example

public interface CustomListener(){
    public void yourMethod();
}


public class CustomListenerAdpter(){
    public void yourMethod(){};
}

Upvotes: 0

Danail Alexiev
Danail Alexiev

Reputation: 7772

You can have separate classes implementing your interfaces and then include them in your Activity using composition:

public class ExampleActivity extends Activity {

    private ExampleInterfaceImplementor mImplementor;
    private AnotherInterfaceImplementor mAnotherImplementor;

}

public class ExampleInterfaceImplementor implements Foo {

}

public class AnotherInterfaceImplementor implements Bar {

}

If you need your Activity to implement the interfaces in order to benefit from polymorphism, you can keep the implements declaration and simply delegate to the implementors.

Upvotes: 1

Related Questions