我有一个包含三个活动(MainActivity,PlayerActivity和ListActivity)的项目。我想将意图从MainActivity
发送到PlayerActivity
,并在PlayerActivity
中选择一个名称,然后将其再次传递给MainActivity.
我写了另一种从ListActivity
向Mainactivity
发送数据的意图。
MainActivity
到ListActivity
的效果很好,也MainActivity
到PlayerActivity.
都很完美,但是当PlayerActivity
将Intent发送到MainActivity
时,我得到了一个空意图
这是我的代码:
从ListActivity发送:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
int buttonId = bundle.getInt("buttonID");
String name = parent.getItemAtPosition(position).toString();
Intent sendIntentToMainActivity = new Intent(PlayersActivity.this, MainActivity.class);
Bundle bundle1 = new Bundle();
bundle1.putString("name", name);
bundle1.putInt("buttonId", buttonId);
startActivity(sendIntentToMainActivity);
}
});
进入MainActivity:
@Override
protected void onNewIntent(Intent intent) {
if (intent != null) {
setIntent(intent);
Log.d("xxx", "Intent is null");
}
}
@Override
protected void onResume() {
super.onResume();
Intent intent = getIntent();
Bundle bundle = new Bundle();
int id = bundle.getInt("buttonID");
String name = bundle.getString("name");
if (id == mButton_first_group_frist_name.getId()) {
mButton_first_group_frist_name.setText(name);
} else if (id == mButton_first_group_second_name.getId()) {
mButton_first_group_second_name.setText(name);
} else if (id == mButton_second_group_frist_name.getId()) {
mButton_second_group_frist_name.setText(name);
} else if (id == mButton_second_group_second_name.getId()) {
mButton_second_group_second_name.setText(name);
}
}
请帮助并提供建议
答案 0 :(得分:0)
您必须将捆绑软件添加到创建的意图中,当回到onResume时,从意图中获取捆绑软件。您可以这样操作:
Intent sendIntentToMainActivity = new Intent(PlayersActivity.this, MainActivity.class);
Bundle bundle1 = new Bundle();
bundle1.putString("name", name);
bundle1.putInt("buttonId", buttonId);
sendIntentToMainActivity.putExtra("bundle",bundle1);
startActivity(sendIntentToMainActivity);
然后在onResume
内:
Intent intent = getIntent();
Bundle bundle = intent.getBundleExtra("bundle");