按钮单击上的随机文本

时间:2012-05-03 18:32:50

标签: android button

当我按下Button时,我想要以随机顺序显示大约150种不同的文本。每次按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:

} }

我仍然得到错误,我把“&lt; ---- X”我做错了什么?

4 个答案:

答案 0 :(得分:2)

您的onClickListener没有可以调用findViewById()的上下文。我可能会使用你的活动实现点击监听器的设计模式。阅读http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html并搜索“更轻松的点击听众”。

答案 1 :(得分:1)

您必须为按钮添加一个监听器。

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

答案 2 :(得分:0)

在Android文档中,您可以找到如何在按钮单击时执行代码。

http://developer.android.com/reference/android/widget/Button.html

答案 3 :(得分: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.
}