简体   繁体   中英

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

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();

 }

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. ie:

    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);

try this change

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

         //user interface interactions and updates on screen

           mHandler.postDelayed(mTicker, 1000);

        }
    };
    mTicker.run();

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);;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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