I want to separate my OnClick contents in another class.
Is it good to separate the onclick content in another class?
If yes, is my way of coding is the proper way or can someone show me a better way?
public class MainActivity extends AppCompatActivity {
private ButtonsActions mButtonsActions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mButtonsActions = new ButtonsActions(this);
}
@OnClick(R.id.btn1)
public void btnTest1() {
mButtonsActions.btnTest1();
}
@OnClick(R.id.btn2)
public void btnTest2() {
mButtonsActions.btnTest2();
}
}
public class ButtonsActions {
private MainActivity view;
public ButtonsActions(MainActivity view) {
this.view = view;
}
public void btnTest1() {
Toast toast = Toast.makeText(view, "Button 1 clicked!", Toast.LENGTH_SHORT);
toast.show();
}
public void btnTest2() {
Toast toast = Toast.makeText(view, "Button 2 clicked!", Toast.LENGTH_SHORT);
toast.show();
}
}
There is no exact answer to your question.
What is the goal you are trying to achieve?
To me it sounds like you want a separation of concerns.
MVC
Would be great to solve such problems, but unfortunately android app is structured in a way that does not allow you to implement it.So what are the options ?
Well you can still separate concerns, but not the way you are doing it, the code you are putting in a different class, is all related to
UI
such code should be remain inside of the activity because it belongs to the Presentation Layer.What you need to do is abstract all the Business Logic away to separate classes.
You can do the same with Database Logic.
Then you will be able to take it a step further by implementing design pattern as it may fit for example Repository Pattern to make all your db transaction through a service.
Or perhaps you build an API service where all perform all you network task through it.
And finally If you want to even take it further, apply solid principle and dependency injection, create util classes for re-usability and put unit test in place.