【问题标题】:Android Activity doesn't enter onBackPressed() methodAndroid Activity 没有进入 onBackPressed() 方法
【发布时间】:2016-10-21 21:57:17
【问题描述】:

这是我的 Android 应用程序的一个 Activity:现在我只是在测试返回另一个 Activity 是否正常工作。问题是:当我点击后退按钮时,一切正常,但是当我按下 ActionBar 屏幕左上角的后退箭头时,活动没有进入 onBackPressed() 方法(因此其他活动崩溃因为它期望通过的意图)。 关于如何解决这个问题的任何想法?

package com.example.thefe.newsmartkedex;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

/**
 * Created by TheFe on 20/10/2016.
 */

public class MyPokeDetails extends AppCompatActivity {

    int pokeID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_poke_details);

        Intent j = getIntent();
        pokeID = j.getExtras().getInt("id");

        getActionBar();

        Button back = (Button)findViewById(R.id.back);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent (getApplicationContext(), PokemonDetails.class);
                i.putExtra("id", pokeID);
                startActivity(i);
            }
        });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent i = new Intent (getApplicationContext(), PokemonDetails.class);
        i.putExtra("id", pokeID);
        startActivity(i);
    }
}

【问题讨论】:

标签: android android-intent onbackpressed


【解决方案1】:

ActionBarToolbar 上的后退箭头是HomeAsUp 按钮,在onOptionsItemSelected() 中处理。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

【讨论】:

  • @AleTheFe 如您所见,@Abtin Gramian 使用了finish();,而不是创建和启动和意图。这是“回去”的正确方法:)
  • 您还应该在AndroidManifest.xml 中设置android:parentActivityName 以防止出现奇怪的回栈问题。
猜你喜欢
  • 2016-11-27
  • 1970-01-01
  • 2017-01-24
  • 2019-02-01
  • 2020-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多