setOnCheckedChangeListener arguments

牧云@^-^@ 提交于 2019-12-20 07:26:43

问题


    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:

  1. You want the radio button to perform some action when the user changes the selection.

  2. 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()

  3. You should realize that the onCheckedChanged() is called in the moment the event happens, not at the time the listener is passed to the setOnCheckedChangeListener() method - so not at the time of your code example is called!

  4. 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,
    call group.setOrientation(LinearLayout.HORIZONTAL)
  • if "vertical" has been selected,
    call group.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!