我有一个Android程序,在点击按钮后发送到另一个活动。主要是,我想在新窗口中设置文本视图中的文本,使其对应于所选按钮。例如,如果我单击按钮编写器,则下一个新活动应该有一个文本视图,其中显示单词Writers。一切正常,除非我尝试在类别的TextView图标上设置文本。我也尝试在第一个活动中调用此更改,在启动第二个活动之前,它不起作用。 我还提到如果我用setText注释该行,程序就可以正常工作。
private String category;
public final static String CATEGORY_MESSAGE = "e.c.project.CATEGORY";
public void onClick(View v) {
switch(v.getId())
{
case R.id.actors:
category = "actors";
playTheGame(v);
break;
case R.id.cartoons:
category = "cartoons";
playTheGame(v);
break;
case R.id.singers:
category = "singers";
playTheGame(v);
break;
case R.id.writers:
category = "writers";
playTheGame(v);
break;
}
}
public void playTheGame( View view ){
Intent intent = new Intent(this, PlayGame.class);
String category = playGameButton.getText().toString();
intent.putExtra(CATEGORY_MESSAGE, category);
// TextView tv = (TextView) findViewById(R.id.categoryTV);
// tv.setText(category);
startActivity(intent);
}
这是来自第二个活动的OnCreate方法:
private TextView categoryTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
setContentView(R.layout.activity_play_game);
// Show the Up button in the action bar.
setupActionBar();
}
答案 0 :(得分:4)
您需要在setContentView(R.layout.activity_play_game);
之前致电categoryTV = (TextView) findViewById(R.id.categoryTV);
,否则TextView
为null
private TextView, categoryTV;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game); // make this call BEFORE initializing ANY views
Intent intent = getIntent();
String category = intent.getStringExtra(GameCategories.CATEGORY_MESSAGE);
categoryTV = (TextView) findViewById(R.id.categoryTV);
categoryTV.setText(category);
// Show the Up button in the action bar.
setupActionBar();
}
View
中存在Layout
,因此如果您在Layout
,setContentView()
或inflater
充气之前尝试访问其中任何一个,当您尝试在null
NPE
生成setText()