handler.postDelayed没有每秒运行

时间:2017-07-20 18:37:21

标签: android

问题/问题是这些代码行没有重复。

   handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter+= ButtonCounter(Counter);
            Counter+= AutoCounter(Counter, add);
            Display(Counter, myTextView);
        }
    },1000);  

我希望代码每秒重复一次,但它只在程序启动后每秒重复一次。后延迟只应该运行一次。如果是这样,我将使用哪种方法每秒运行而不是只运行一次。

package com.example.navjeevenmann.mytycoon;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 0;
private int timer = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myButton = (Button) findViewById(R.id.button);
    myButton2 = (Button) findViewById(R.id.button2);
    myTextView = (TextView) findViewById(R.id.textView);
    myButton.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View view) {
        }
    });
    myButton2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("Count", Counter);
            startActivity(intent);
            finish();
        }

    });

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter+= ButtonCounter(Counter);
            Counter+= AutoCounter(Counter, add);
            Display(Counter, myTextView);
        }
    },1000);    }

public int ButtonCounter(int Counter) {
    Counter += 1;
    return Counter;
}

public int AutoCounter(int Counter, int add) {
    Counter += add;
    return Counter;
}

public void Display(int Counter, TextView myTextView) {
    String man = String.valueOf(Counter);
    myTextView.setText("$" + man);
}






}

1 个答案:

答案 0 :(得分:2)

尝试在显示(计数器,myTextView)之后放置 handler.postDelayed(this,1000),如下所示:

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Counter+= ButtonCounter(Counter);
        Counter+= AutoCounter(Counter, add);
        Display(Counter, myTextView);
        handler.postDelayed(this, 1000);
    }
},1000);    }