![](/img/trans.png)
[英]How to change text color when Button/TextView is pressed in android
[英]Change Text in TextView Box when Button is pressed
我是编程新手,正在学习用Java开发和构建Android应用程序。
我正在尝试在xml文件上创建一个Dreidel游戏,我有一个按钮,一个imageview和一个TextView(我将在稍后保持得分,我可以很容易地自己弄清楚这一点,我想)。
但目的是当我按下按钮时,随机数产生器会产生0-3之间的数字,
如果为0,我希望TextBox显示“您什么都没有”如果为1,我希望TextBox显示其他内容如果为2,我希望TextBox显示其他内容如果为3,我希望TextBox显示其他内容
这是代码。 当我在Android模拟器中运行它时,它启动了,但是当我单击按钮时什么也没有发生
package com.secondtry;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
numGen.nextInt(4);
if (numGen.nextInt() == 0)
{
display.setText("You get nothing");
}
else if (numGen.nextInt() == 1)
{
display.setText("You get half!");
}
else if (numGen.nextInt() == 2)
{
display.setText("You get it all");
}
else if (numGen.nextInt() == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
在您的情况下使用numGen.nextInt(4)代替numGen.nextInt()。 将其值保存在变量(例如x)中,并在每种条件下使用该值。
您可以尝试以下方法:
int ran = numGen.nextInt(4);
switch (ran){
case 0:
display.setText("You get nothing");
break;
case 1:
display.setText("You get half!");
break;
case 2:
display.setText("You get it all");
break;
case 3:
display.setText("Chip in a coin");
break;
}
您需要使用类似以下内容的onCreate定义按钮
final Button spinButton = (Button) findViewById(R.id.spinbuttonIdInXML);
或将onClick拉到onCreate之外:
@Override
public void onCreate(Bundle savedInstanceState) {
...
}
@Override
public void onClick(View v) {
...
}
像这样在OnCreate中定义您的按钮。
spinButton = (Button)findViewById(R.id.urbuttonid);
更新尝试
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button spinButton;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinButton = (Button)findViewById(R.id.ButtonId);
display = (TextView) findViewById(R.id.widget34);
spinButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(4);
if (rNumber == 0)
{
display.setText("You get nothing");
}
else if (rNumber == 1)
{
display.setText("You get half!");
}
else if (rNumber == 2)
{
display.setText("You get it all");
}
else if (rNumber == 3)
{
display.setText("Chip in a coin");
} }
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.