按下按钮生成随机句子,代码看起来正确但不起作用

时间:2010-07-20 00:55:04

标签: java android string arrays random

我不确定这里有什么问题,我想做的就是从我的阵列中随机抓取一个项目。这就像一个随意的句子。按下按钮后再生成另一个。我的所有代码看起来都不错,但是当我按下按钮时它会导致崩溃。任何想法?

package com.my.package;


import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.view.View.OnClickListener;

public class Randomsentence extends Activity implements OnClickListener{


    private String[] myString;
    private static final Random rgenerator = new Random();
    private TextView tv;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Resources res = getResources();

    myString = res.getStringArray(R.array.myArray); 

    String q = myString[rgenerator.nextInt(myString.length)];

    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);

    View nextButton = findViewById(R.id.next_button);
    nextButton.setOnClickListener(this);

}

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.next_button:
        tv.setText(myString[rgenerator.nextInt(myString.length)]);
        break;
    }

}
    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu3, menu);
        return true;
    }

@Override
public boolean onOptionsItemSelected (MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu:
            startActivity(new Intent(this, Main.class));
            return true;
        case R.id.startnhie:
            startActivity(new Intent(this, startnhie.class));
            return true;

}
return false;
    }



}

1 个答案:

答案 0 :(得分:3)

onCreate()中,更改

TextView tv = (TextView) findViewById(R.id.text1);

tv = (TextView) findViewById(R.id.text1);

因为您已将TextView tv声明为实例变量。