How to set timer in android?

后端 未结 21 908
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  一向
    一向 (楼主)
    2020-11-22 01:32

    He're is simplier solution, works fine in my app.

      public class MyActivity extends Acitivity {
    
        TextView myTextView;
        boolean someCondition=true;
    
         @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.my_activity);
    
                myTextView = (TextView) findViewById(R.id.refreshing_field);
    
                //starting our task which update textview every 1000 ms
                new RefreshTask().execute();
    
    
    
            }
    
        //class which updates our textview every second
    
        class RefreshTask extends AsyncTask {
    
                @Override
                protected void onProgressUpdate(Object... values) {
                    super.onProgressUpdate(values);
                    String text = String.valueOf(System.currentTimeMillis());
                    myTextView.setText(text);
    
                }
    
                @Override
                protected Object doInBackground(Object... params) {
                    while(someCondition) {
                        try {
                            //sleep for 1s in background...
                            Thread.sleep(1000);
                            //and update textview in ui thread
                            publishProgress();
                        } catch (InterruptedException e) {
                            e.printStackTrace(); 
    
                    };
                    return null;
                }
            }
        }
    

提交回复
热议问题