如何使用getIntent()更新主要活动?

时间:2016-02-28 22:28:49

标签: java android android-intent

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //identify object

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    **title = (TextView)findViewById(R.id.theTitle);
    Intent intent = getIntent();
    String Title = intent.getExtras().getString("name");
    title.setText(Title);**
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action

    } else if (id == R.id.nav_gallery) {
        Intent intent = new Intent(this, addCounter.class);
        startActivity(intent);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

当nav_gallery = true时,它会将我带到activity2,其中包含以下代码:

    public void addOk(){
    String sendName = name.getText().toString();
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("name", sendName);
    startActivity(intent);
}

我想将来自activity2的信息发送回主要活动。我的getIntent()是在错误的地方吗?

1 个答案:

答案 0 :(得分:0)

你的getIntent()方法在onCreate方法中。 但onCreate只在创作时被调用一次。如果MainActivity仍在堆栈中,则没有理由再次调用onCreate()。

您应该尝试在onResume()或onStart()中插入代码。