Android: Call listener manually from java code

两盒软妹~` 提交于 2019-12-08 11:31:30

问题


Is there any way to call a listener manually from code?

More background information: I use a Spinner and a DatePicker. With the Spinner you can choose a reason for staying at home (maybe your ill, maybe you have vacation) and with the DatePicker you can choose the date how long you will not be available. With these two pieces of information I build up a string for a TextView and show the same data in a compact way. The building process for the string is set by some listeners which recognize changes on one of the two controls and build and set up the new string. If I start the program and read some data from a server the string will not be build (clearly because nothing changed and no listener will called).

The workaround is to build the string in my own onLoaddata() method. But I think it would be smoother way to call one listener to build the string for me. I also can "call" a listener if I just do some fake .updateDate but I don't think it’s a good idea to create useless calls...

Maybe someone of you have a good hint for me?


回答1:


Use the following pattern:

public class YourActivity extends Activity implements OnClickListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        // Some initialization here
        findViewById(R.id.some_button).setOnClickListener(this);

        ...

        // Here you want to update your view
        updateTextView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.some_button:
            // Here you also want to update your view
            updateTextView();
            break;

        ...

        }
    }

    private void updateTextView() {
        // Here you update your view
        ...
    }
}


来源:https://stackoverflow.com/questions/9901708/android-call-listener-manually-from-java-code

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