首先,
执行此操作时,您正在设置对象的引用 ID:
randomUSA.setText(pop +"");
这就是为什么你会收到奇怪的文字。
改用这个,
randomUSA.setText(pop.getText())
第二,
在我看来,Random.nextInt(2) 永远不会返回 2,它只会返回 0 或 1。如果您正在寻找 1 或 2 作为结果,请改用 (randomStat.nextInt(2) + 1)。
第三,
使用 ID 引用您的按钮,并设置点击监听器,
Button refresherButton = (Button) findViewById(R.id.refersherButton);
refresherButton .setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
randomUSA.setText(pop.getText());
}
});
使用您的代码更新:
setContentView(R.layout.activity_main);
pop = (TextView) findViewById(R.id.popUSA);
poprank = (TextView) findViewById(R.id.poprankUSA);
// I would suggest you to pre-set something into this two textview,
// so that you can get it later.
// But of course you should set it base on your application logic, not hardcode
pop.setText("Population: 316,668,567");
poprank.setText("Population Rank: 3");
randomUSA = (TextView) findViewById(R.id.randomUSA);
bRandomusa = (Button) findViewById(R.id.bRandom);
Random randomStat = new Random();
int firstRandom = randomStat.nextInt(2);
if (firstRandom == 0) {
randomUSA.setText(pop.getText());
}else if (firstRandom == 1) {
randomUSA.setText(poprank.getText());
}
//Use setTag here, for cleaner codes
bRandomusa.setTag(randomStat);
bRandomusa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random randomStat = (Random) v.getTag();
int random = randomStat.nextInt(2);
if (random == 0) {
randomUSA.setText(pop.getText());
}else if (random == 1) {
randomUSA.setText(poprank.getText());
}
}
});