Back按钮退出应用程序,而不是回到MainActivity



我有两个活动,MainActivityQuestionActivity
MainActivityQuestionActivity的父母。问题是当我按QuestionActivity的后退按钮/图标时,应用程序退出而不是返回MainActivty
我记下了以下内容,但是应用程序不起作用。

清单文件

       <activity
            android:name=".question.QuestionActivity"
            android:parentActivityName=".MainActivity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>

我将上面的内容更改为此,但问题仍然存在

            <activity
               android:name="full_package_name.question.QuestionActivity"
               android:parentActivityName="full_package_name.MainActivity">
                <meta-data
                    android:name="android.support.PARENT_ACTIVITY"
                    android:value="full_package_name.MainActivity" />
            </activity>

QuestionActivty

public class QuestionsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_questions);
        Toolbar toolbar = (Toolbar) findViewById(R.id.questions_toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            //getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        QuestionsStatePagerAdapter questionsStatePagerAdapter = new QuestionsStatePagerAdapter(getSupportFragmentManager());
        ViewPager mViewPager = (ViewPager) findViewById(R.id.question_container);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(questionsStatePagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.question_tabs);
        tabLayout.setupWithViewPager(mViewPager);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_questions, menu);
        return true;
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // Respond to the action bar's Up/Home button
            case android.R.id.home:
                Intent upIntent = NavUtils.getParentActivityIntent(this);
                if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                    // This activity is NOT part of this app's task, so create a new task
                    // when navigating up, with a synthesized back stack.
                    TaskStackBuilder.create(this)
                            // Add all of this activity's parents to the back stack
                            .addNextIntentWithParentStack(upIntent)
                            // Navigate up to the closest parent
                            .startActivities();
                } else {
                    // This activity is part of this app's task, so simply
                    // navigate up to the logical parent activity.
                    NavUtils.navigateUpTo(this, upIntent);
                }
                //Toast.makeText(this, "Up Button is clicked!", Toast.LENGTH_SHORT).show();
                return true;
        }
        return true;
    }
}

编辑添加MainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener{
    public SessionManager sessionManager;
    public SQLiteHandler dbHandler;
    private DrawerLayout mDrawerLayout;
    private NavigationView navigationView;
    private View navHeader;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //create the toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //create a recycleView for the user landing page
        TextView userTextView = (TextView) findViewById(R.id.txt_username);
        //create dbHandler instance
        dbHandler = new SQLiteHandler(getApplicationContext());
        //get current user details
        HashMap<String, String> currentUser = dbHandler.getUserDetails();
        String currentUserName = currentUser.get("username");
        String auth_key = currentUser.get("auth_key");
        userTextView.setText(auth_key+"n" + currentUserName);
        //in case there is no value for auth_key
        //get this guy back to the login Page hehe
        //just for enough security
        if (auth_key.isEmpty()) {
            // Launch Login activity
            Intent intent = new Intent(MainActivity.this,
                    LoginActivity.class);
            startActivity(intent);
            finish();
        }
        Toast.makeText(this,"HEY",Toast.LENGTH_LONG).show();
        //drawer initialization
        mDrawerLayout = (DrawerLayout) findViewById(R.id.app_drawer_layout);
        navigationView = (NavigationView) findViewById(R.id.app_navigation);
        //setup the header
        navHeader = navigationView.getHeaderView(0);
        //nav texts
        TextView headerUser = (TextView) navHeader.findViewById(R.id.header_user);
        headerUser.setText(currentUserName);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.app_navigation);
        navigationView.setNavigationItemSelectedListener(this);
        //create sessionManger instance
        //THE CONTEXT IS SIMPLY THE mAIN ACTIVITY
        sessionManager = new SessionManager(getApplicationContext());
        sessionManager.isLoggedIn();
        //set up the drawer layout
        //fetch all the current questions/recent questions
        //create a snackbar for asking a question
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.submit_question);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //go to ask question page
                //activity or Fragment?
                //lets go for fragments
                // Launch Login activity
                Intent intent = new Intent(MainActivity.this,
                        QuestionFormActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    //override methods
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        Intent intent;
        switch (id){
            case  R.id.nav_blog:
                // Launch sales activity
                intent = new Intent(
                        MainActivity.this,
                        BlogActivity.class);
                startActivity(intent);
                finish();
                break;
        }
        return false;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.app_drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        //The R.id.action_logout is found in the res/menu folder
        int id = item.getItemId();
        switch (id){
            case  R.id.action_logout:
                logoutCurrentUser();
                break;
            //implement more actions here
            //pull to refresh
        }
        return super.onOptionsItemSelected(item);
    }

}

我错过了什么吗?

更改您的onBackPressed方法,例如Bellow

@Override
public void onBackPressed(){
//remove super.onBackPressed() and you can handle intent to mainActivity or 
//any other activity
}

删除super.onBackPressed()

后,您也可以转到manifest.xml并将活动的父母设置为MainAttivity

从第二个活动中删除元数据

<meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="full_package_name.MainActivity" />

删除

<activity
        android:name=".question.QuestionActivity"></activity>

足够

并确保在编写startActivity(intent)时,请勿在

之后添加finish()

足以显示回到按钮

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

在主要活动中使用意图和起始性

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);

在次级覆盖中下一个功能

@Override
public boolean onSupportNavigateUp() {
    finish();
    return true;
}

(或)

@Override
public boolean onNavigateUp() {
    finish();
    return true;
}

您可以使用finish();结束辅助活动并返回MainActivity

您已经在质疑 I.EonBackPressed

中已经有了方法

将代码放在

  @Override
public void onBackPressed() {
    super.onBackPressed(); //do what ever you want here like going back to your desired screen.
    }

首先初始化后背按钮的工具栏栏

 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
          getSupportActionBar().setDisplayHomeAsUpEnabled(true);

然后回电按钮方法此代码足以转到以前的活动,否则您可以在onBackPressed中使用意图方法来返回

//method on back button click
    @Override
    public void onBackPressed() {
        super.onBackPressed();
/*OR
  Intent forgot_password = new Intent( AddItemActivity.this,  NavigationAndHomeActivity.class);
                startActivity(forgot_password);
                finish();
        }*/

BACK按钮单击功能

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

最新更新