我正在开展一个项目我有两个类别的板球运动员和动物在一个活动上作为按钮和一个文本视图在其他活动我想要更改文本视图的文本,当我按下按钮即如果Cricketer然后将文本设置为板球运动员同样适合动物。
两个按钮的OnClick Listner:On Activity 1
public void onClickcricketer(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btncricket);
String crickettext = b.getText().toString();
i.putExtra("Cricket",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,offlineQuestionsession.class);
final Button b = (Button)findViewById(R.id.btnanimal);
String animaltext = b.getText().toString();
i.putExtra("Animal",animaltext);
startActivity(i);
}
活动2的代码:
Bundle cricketData = getIntent().getExtras();
if (cricketData == null){
return;
}
String Cricket = cricketData.getString("Cricket");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
Bundle AnimalData = getIntent().getExtras();
if (AnimalData == null){
return;
}
String Animal = AnimalData.getString("Animal");
final TextView a = (TextView)findViewById(R.id.txtCategryShow);
a.setText(Animal);
此方法只在文本视图中显示动物文本..当我点击Crcketer按钮时,它不显示任何内容
答案 0 :(得分:1)
首先执行onClick方法:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String toExtra = "" + btn.getText();
Intent i = new Intent(this,NextActivity.class);
i.putExtra("key",toExtra);
}
});
然后在新的Activity OnCreate方法中添加:
Intent i = getIntent();
String fromExtra = intent.getStringExtra("key");
最后将setText设置为TextView:
txt.setText(fromExtra)
答案 1 :(得分:0)
这样做是正确的,再次看到你的代码,在同一个TextView上你设置的文本Animal在点击板球时是空的。
在第二项活动中尝试此操作:
String Cricket = getIntent().getStringExtra("KEY");
final TextView c = (TextView)findViewById(R.id.txtCategryShow);
c.setText(Cricket);
制作这样的方法:
public void onClickcricketer(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_cricket);
String crickettext = b.getText().toString();
i.putExtra("KEY",crickettext);
startActivity(i);
}
public void onClickanimal(View view){
Intent i = new Intent(this,YourNewActivity.class);
final Button b = (Button)findViewById(R.id.txv_animal);
String animaltext = b.getText().toString();
i.putExtra("KEY", animaltext);
startActivity(i);
}