1

我想将我的 Android 应用程序中的 TextView 随机设置为同一类中的另一个 TextView。我试过这个:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pop = (TextView) findViewById(R.id.popUSA);
poprank = (TextView)findViewById(R.id.poprankUSA);
randomUSA = (TextView) findViewById(R.id.randomUSA);
Random randomStat = new Random();
int random = (randomStat.nextInt(2));

if (random == 1){
randomUSA.setText(pop +"");
if (random == 2){
randomUSA.setText(poprank+"");          
}};

}

它没有用。它会向我显示一些随机文本,并且在我重新打开应用程序时没有改变。另外,有人可以告诉我如何制作一个按钮来刷新 TextView 并将其设置为不同的随机按钮。谢谢你

4

1 回答 1

0

首先,

执行此操作时,您正在设置对象的引用 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());
        }
    }
});
于 2013-05-02T02:17:55.173 回答