Runnable Handler not executing inside fragment. Could not start a runnable

大城市里の小女人 提交于 2020-06-17 07:54:29

问题


I have a runnable inside a fragment. The runnable is meant to update the textviews as well as receive input using buttons. But the program does not enter even once inside the runnable.

Please help. What am I doing wrong. Thanks. The code is as follows. I have buttons and textviews inside the runnable.

public class TodayFragment extends Fragment {
//initialisations

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//UI initialisations

Handler mHandler = new Handler();
Runnable mTicker = new Runnable() {
            @Override
            public void run() {

//user interface interactions and updates on screen

    mHandler.postDelayed(mTicker, 1000);


   mTicker.run();

 }

回答1:


try this change

mTicker = new Runnable() {
        public void run() {

         //user interface interactions and updates on screen

           mHandler.postDelayed(mTicker, 1000);

        }
    };
    mTicker.run();



回答2:


it seems you wanna change your views in every 1 second. if you say so you should execute your handler outside your runnable method aswell. i.e:

    Handler mHandler = new Handler();
    Runnable mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen
            // if you want to run this handler only once then delete below line
            mHandler.postDelayed(mTicker, 1000);

        }
    };

mHandler.postDelayed(mTicker, 1000);



回答3:


It's work for me.

public class TodayFragment extends Fragment {
//initialisations
Runnable mTicker;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final Handler mHandler = new Handler();
    mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen

            mHandler.postDelayed(mTicker, 1000);

            }
        };

    mHandler.postDelayed(mTicker, 1000);

    return inflater.inflate(R.layout.fragment_today, container, false);;

}


来源:https://stackoverflow.com/questions/26314406/runnable-handler-not-executing-inside-fragment-could-not-start-a-runnable

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