액티비티에는 로직들이 별도의 클래스에 있으면 생각보다 쉽게 재사용이 가능하겠죠?
MVP나 MVVM이라고 하는 디자인 패턴을 이용하세요. 로직에 뷰에 결합되 있으면 재사용이 엄청 힘들겁니다. 테스트도 쉽지 않구요.
pubic class MainActivity extends AppCompatActivity implements MainView {
private MainPresenter presenter;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
presenter = new MainPresenterImpl(this);
findViewById(R.id.myButton).setOnClick {
presenter.doAction();
}
}
public void doSomething() {
// Do Something
}
}
interface MainView {
void doSomething()
}
interface MainPresenter {
void doAction();
}
public class MainPresenterImpl implements MainPresenter {
private final MainView view;
public MainPresenter(MainView view) {
this.view = view;
}
@Override
public void doAction() {
if (view == null) return
// Do Action
}
}
위의 예제는 MVP 패턴의 예제인데 핵심은 주요 로직은 Presenter 로 옮겨가고 Activity와 Presenter는 interface를 통해 이벤트를 주고 받습니다. 이렇게 하면 서로 의존성이 없어지기 때문에 프레그먼트에서 MainView 인터페이스를 구현하면 MainPresenter를 재사용할 수 있습니다.