每秒在android中重复一行代码

时间:2017-07-20 01:27:29

标签: android repeat

这是我想重复的一行。

     handler.postDelayed(runnableCode, 1);

这个应用程序是一个大亨应用程序,所以用户可以购买升级,如果他们点击按钮获得$$,所以当他们购买升级时,保持最新的价值是必需的。

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 Test = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        handler.postDelayed(runnableCode, 1);
        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) {
                ButtonCounter(Counter);
            }
        });
        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();
            }
        });

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

private Runnable runnableCode = new Runnable() {
    @Override
    public void run() {
        // Do something here on the main thread
        Counter = AutoCounter(Counter,Test);
        Display(Counter, myTextView);

    }
    };


   }

2 个答案:

答案 0 :(得分:0)

handler.postDelayed(runnableCode, 1);

onResume()方法中调用该行。每当用户点击按钮获取$$时,请确保向用户显示AlertDialog。由于每次用户试图购买$$时都会弹出AlertDialogonResume()将被调用。

答案 1 :(得分:0)

试试这个

  

    private void startAnimation() {
           countDownTimer = new CountDownTimer(700, 500) {
                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                 //your code to repeat
                    }
                    start();
                }
            }.start();
        }