[英]Why does my app crash when I press a button and how to fix it
I am trying to make a basic dice roller for a card game. 我正在尝试制作纸牌游戏的基本骰子滚轴。 It is on the second screen of two. 它在两个的第二个屏幕上。 The screen opens fine when I press the button to open it, but when I click the dice button the app simply crashes. 当我按下按钮将其打开时,屏幕打开正常,但是当我单击骰子按钮时,应用程序便崩溃了。 I am using the newest version of Android Studio. 我正在使用最新版本的Android Studio。 Here's my code: 这是我的代码:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
import static android.R.attr.value;
public class Extras extends AppCompatActivity implements OnClickListener{
Button btn1;
TextView numberGenerator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extras);
btn1 = (Button) findViewById(R.id.diceButton);
btn1.setOnClickListener(this);
numberGenerator = (TextView)findViewById(R.id.numberGenerator);
}
@Override
public void onClick(View v) {
int min = 1;
int max = 6;
Random random = new Random();
int value = random.nextInt(max - min) + min;
numberGenerator.setText(value+"");
if (v == btn1) {
numberGenerator.setText(value);
}
}
...
}
Your app is crashes because you are trying to put int value to the setText() method. 您的应用程序崩溃是因为您试图将int值添加到setText()方法中。
Here: 这里:
if (v == btn1) {
numberGenerator.setText(value);
}
Try instead: 请尝试:
if (v == btn1) {
numberGenerator.setText(String.valueOf(value));
}
If this does not work post your stacktrace. 如果这不起作用,请发布您的堆栈跟踪信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.