繁体   English   中英

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

[英]How do I update the Main Activity using getIntent()?

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);
}

我想将信息从活动2发送回主要活动。 我的getIntent()是否在错误的位置?

您的getIntent()方法位于onCreate方法内部。 但是onCreate在创建时仅被调用一次。 而且,如果MainActivity仍在堆栈中,则没有理由再次调用onCreate()。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM