问题
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.orientation);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.horizontal:
group.setOrientation(LinearLayout.HORIZONTAL);
break;
case R.id.vertical:
group.setOrientation(LinearLayout.VERTICAL);
break;
}
}
});
What is radioGroup.setOnCheckedChangeListener eactly? Is it a method? What are it's arguments then?
回答1:
setOnCheckedChangeListener()
is a method which sets a listener which listens on a specific action.
The idea is this:
You want the radio button to perform some action when the user changes the selection.
The system tells the radio button whenever the selection has been changed. If the radio button have a listener set, the listener "listens" to the event - there is a mechanism which performs some action by calling its method
onCheckedChanged()
You should realize that the
onCheckedChanged()
is called in the moment the event happens, not at the time the listener is passed to thesetOnCheckedChangeListener()
method - so not at the time of your code example is called!The class
new RadioGroup.OnCheckedChangeListener()
is needed to pass the listener's behaviour - up to Java 7 inclusive, you cannot pass just a method without a class. Since Java 8 you may do more easily it using lambda expressions, but don't bother with it now.
This is quite an advanced topic, I recommend you to study this first:
- Listener design pattern (a.k.a. Observer)
- Anonymous classes
You may think about it in the simplified way. Your code has the following meaning:
Dear
radioGroup
,
the thing which you should do whenever the check has been changed is this:
- if "horizontal" has been selected,
callgroup.setOrientation(LinearLayout.HORIZONTAL)
- if "vertical" has been selected,
callgroup.setOrientation(LinearLayout.VERTICAL)
N.B. Don't do it now, do it only when the check has been changed!
来源:https://stackoverflow.com/questions/24170564/setoncheckedchangelistener-arguments