簡體   English   中英

Android Java類具有很多偵聽器接口

[英]Android java class with a lot of Listeners Interfaces

通常,我的Activity類必須實現2個以上的接口,這使我的類非常龐大。

在Swift中,您可以使用擴展程序解決此問題

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
}

如何用Java處理呢?

您可以使用單獨的類來實現您的接口,然后使用組合將它們包括在Activity中:

public class ExampleActivity extends Activity {

    private ExampleInterfaceImplementor mImplementor;
    private AnotherInterfaceImplementor mAnotherImplementor;

}

public class ExampleInterfaceImplementor implements Foo {

}

public class AnotherInterfaceImplementor implements Bar {

}

如果您需要Activity來實現接口以從多態中受益,則可以保留實現聲明,並簡單地委托給實現者。

創建具有一定數量功能的接口,而其他適配器則以空主體實現該接口。

然后包括該適配器,而不是偵聽器和覆蓋方法。

這是Java語言標准

例如

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


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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM