Reputation: 12236
Is this generally a good practice to adopt?
I am working through the tutorials and got to the part where button listeners are being implemented:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
//and here is the anonymous inner class
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
Am I better off learning this style or is there another way I should be learning this for the sake of good practice? It seems a little counter to my basic understanding of OOP where things seem to be... separated and modularized, if that makes sense.
Upvotes: 0
Views: 111
Reputation: 44228
Yes, there is another way that I often prefer (especially in big projects), your class can implement listeners
So your Activity/Fragment
can be declared this way
public class MyActivity implements View.OnClickListener{
and your view object, button in this case, would set it's listener this way
mTrueButton.setOnClickListener(this)
and then you would have another class called onClick()
where ALL of your clickable view elements can now have their code
@Override
public void onClick(View v){
switch(v.getId()){
case R.id.true_button:
break;
}
}
Upvotes: 1