我不确定这里有什么问题,我想做的就是从我的阵列中随机抓取一个项目。这就像一个随意的句子。按下按钮后再生成另一个。我的所有代码看起来都不错,但是当我按下按钮时它会导致崩溃。任何想法?
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;
}
}
答案 0 :(得分:3)
在onCreate()
中,更改
TextView tv = (TextView) findViewById(R.id.text1);
到
tv = (TextView) findViewById(R.id.text1);
因为您已将TextView tv
声明为实例变量。