I'm confused about different uses of setOnClickListener
in an Activity button actions.
I found a various solutions but I'm sure there is some best/worse approach to implement it and also some "because".
I would understand (as subject) which is the best approach and which (and why) are not.
call a private function in activity (class) and set the listener and all casts in it:
public class MainActivity extends AppCompatActivity { Private Button myButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OnClickButton(); } private void OnClickButton(){ myButton = (Button)findViewById(R.id.Button1); myButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // button actions } }); } }
set a setOnClickListener in activity and then call appropriate function: (In this case I don't understand also why the view is defined as final in onClick)
public class MainActivity extends AppCompatActivity { Private Button myButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myButton.setOnClickListener(onClickListener); } private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(final View v) { // button actions } }
- simply as a function with argument myView by linking the function in xml file:
ON MAINACTIVITY.XML ADD:
android:onClick="onButtonClick"
ON MAINACTIVITYCLASS:
public class MainActivity extends AppCompatActivity {
Private Button myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v){
// button actions
}
}
NOTE: I found (need comfirms) that 3° way is not a good practice because is not supported in framesets.
If you have some more strong good coded solution, please add it.
Please try to clear the good practice and bad-practice differences, and why something is more correct or instead is a bad solution.
Hoping this could be useful to other people, I wrote this post also because many post I read were very old. Thank you.