如何将TextView设置为同一类中的其他随机TextView?

时间:2013-05-01 23:50:10

标签: android text random textview

我想在我的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的按钮,并将其设置为一个不同的随机。 谢谢

1 个答案:

答案 0 :(得分:0)

首先,

执行此操作时,您正在设置对象的引用ID:

randomUSA.setText(pop +"");

这就是为什么你会得到奇怪的文本。

请改用

randomUSA.setText(pop.getText()) 

其次,

我的意见中的Random.nextInt(2)将永远不会返回2,它只会返回0或1。 如果您要查找1或2,请使用(randomStat.nextInt(2)+ 1)。

第三,

使用ID引用您的按钮,并设置on click listener,

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());
        }
    }
});