2012-05-03 61 views
0

我有大约150种不同的文本,当我按Button时,我想按随机顺序显示。每次按Button时都会有一个新的。我已经想通了这个代码:单击按钮上的随机文本

Random myRandom = new Random(); 
    TextView textblondin = (TextView) findViewById(R.id.textblondin); 
    switch(myRandom.nextInt() %3) { 
     case 0: 
     textblondin.setText("Text 1"); 
     break; 
     case 1: 
     textblondin.setText("Text 2"); 
     break; 
     case 2: 
    textblondin.setText("Text 3"); 
    break; 
     default: 
    break; 
    } 
} 
} 

我可以得到它连接到一个Button。有人知道怎么做吗?

public class Blondinskamt extends Activity {   <----X 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.blondintext); 
    View myRandom = findViewById(R.id.myRandom); 
    myRandom.setOnClickListener(null); 


    myRandom.setOnClickListener(new View.OnClickListener() { 
    Random myRandom = new Random(); 
    TextView textblondin = (TextView) findViewById(R.id.textblondin); <----X 
    switch(myRandom.nextInt() %3) { 
    case 0: 
     textblondin.setText("Skämt"); 
     break; 
    case 1: 
     textblondin.setText("Roligt"); 
     break; 
    case 2: 
     textblondin.setText("kul kul kul kul"); 
     break; 
     default: 

}}

我仍然得到错误,在这里我把 “< ---- X” 什么我做错了什么?

回答

0

存储中的所有150串在一个ArrayList并显示由随机生成的数字的文本。

样本;

ArrayList<String> arr_str = new ArrayList<String>(); 

arr_str.add(String Parameter) // add the all strings in arraylist by using the method. 

Random randomGenerator = new Random(); 
int randomInt = 0; 

within the button onclick listener write the following code. 
{ 
    randomInt = randomGenerator.nextInt(149); // this will generate random number b/w 0 to 149. 
textView.setText(arr_str.get(randomInt)); // you can get the n th number of string stored in the arraylist. 
} 
+0

use Button myRandom = findViewById(R.id.myRandom); myRandom.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ //单击执行操作 } }); –

1

你必须添加一个监听器到你的按钮。

textblondin.setOnClickListener(new View.OnClickListener() { 
    ... your code here ... 
}