package com.example.chirag.example;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView TV;
Button upbutton;
Button downbutton;
TextView score;
String n1;
int bool=0;
int a;
int b;
int sc=0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView TV = (TextView)findViewById(R.id.TV);
TextView score = (TextView)findViewById(R.id.score);
Button upbutton = (Button) findViewById(R.id.upbutton);
Button downbutton = (Button) findViewById(R.id.downbutton);
Button start = (Button) findViewById(R.id.start);
n1 = generate();
TV.setText(n1);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
start();
}
});
}
String generate()
{
TextView TV = (TextView)findViewById(R.id.TV);
int n = new Random().nextInt(20);
String s = String.valueOf(n);
return s;
}
void start() {
Runnable myRunnable = new Runnable() {
@Override
public void run()
{while (bool == 0) {
final TextView TV = (TextView) findViewById(R.id.TV);
final TextView score = (TextView) findViewById(R.id.score);
Button upbutton = (Button) findViewById(R.id.upbutton);
Button downbutton = (Button) findViewById(R.id.downbutton);
Button start = (Button) findViewById(R.id.start);
String n2 = generate();
TV.setText(n2);
a = Integer.valueOf(n1.toString());
b = Integer.valueOf(n2.toString());
if (a > b) {
downbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String n3 = generate();
TV.setText(n3);
a = b;
b = Integer.valueOf(n3.toString());
score.setText("Score" + (sc + 1));
}
});
upbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TV.setText("Game Over");
bool = 1;
}
});
} else {
upbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String n3 = generate();
TV.setText(n3);
a = b;
b = Integer.valueOf(n3.toString());
score.setText("Score" + (sc + 1));
}
});
downbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TV.setText("Game Over");
bool = 1;
}
});
}
}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
}
我把代码放在了runnable中。逻辑似乎是正确的,但它不起作用。 generate方法创建一个新数字并将其显示在' TV'中。单击开始时,将生成一个新数字,并将第二个数字与第一个数字进行比较。如果按下正确的按钮(向上或向下),则分数增加并继续处理。 "游戏结束"如果点击了错误的按钮
答案 0 :(得分:1)
您无法从其他线程触摸UI。 Android中的所有UI任务都应该在主线程中执行,也称为UI线程。
这一行(例如)尝试从非主线程的run()
命令内部影响ui:
TV.setText(n2);
有关如何与UI线程通信的信息,请参阅this tutorial