简体   繁体   English

在Fragment中每秒执行一次方法-第二次运行时为NULL

[英]Executing method every second in Fragment - NULL Value on second run

We are getting values from onCreate method for someID. 我们从onCreate方法获取someID的值。 When the the onCreateView method runs the first time, everything is fine. 当onCreateView方法第一次运行时,一切都很好。 However, on the second run (after the 1000 interval), the someID value is NULL. 但是,在第二次运行中(在1000个间隔之后),someID值为NULL。 How can we make sure that this someID value will be sticky? 我们如何确保该someID值是粘性的? Keep in mind that this thread exists in a Fragment 请记住,该线程存在于片段中

@Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            someID = getArguments().getString(SOME_ID_KEY);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
            View v = inflater.inflate(R.layout.fragment_game, container, false);
            Toast.makeText(getActivity(), someID, Toast.LENGTH_SHORT).show();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
                    handler.postDelayed(this, 1000);
                }
            }, 1000);

You can do it like this 你可以这样

private void printId(){
    handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
                printId();
            }
        }, 1000);
}

and in your onCreateView replace all the handler code with: 并在您的onCreateView中将所有处理程序代码替换为:

pirntId();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM