Android 如何在按下手机的后退按钮时加载Main活动

Android 如何在按下手机的后退按钮时加载Main活动,android,back-button,Android,Back Button,我有一个MainActivity,其中有一个NavigationDrawer。在抽屉的菜单中,每个项目都会启动一个新的活动。现在,当我从任何这些活动中按下后退按钮时,我会在一个空白页中结束,当我再次按下它时,它会转到主活动。我想要的是直接转到主活动 myMainActivity.java: package com.defcomm.invento; import android.support.design.widget.CollapsingToolbarLayout; import andro

我有一个
MainActivity
,其中有一个
NavigationDrawer
。在抽屉的菜单中,每个项目都会启动一个新的活动。现在,当我从任何这些活动中按下后退按钮时,我会在一个空白页中结束,当我再次按下它时,它会转到主活动。我想要的是直接转到主活动

my
MainActivity.java

package com.defcomm.invento;

import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.defcomm.invento.NavigationDrawerActivity;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

public class INVENTO extends AppCompatActivity {

private Toolbar toolbar;
private CoordinatorLayout mCoordinator;
private CollapsingToolbarLayout mCollapsableLayout;
private NestedScrollView nestedScrollView;
private ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    mCoordinator= (CoordinatorLayout) findViewById(R.id.coordinator_layout);
    mCollapsableLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    toolbar= (Toolbar) findViewById(R.id.appbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    mCollapsableLayout.setTitle(getResources().getString(R.string.app_name));
    nestedScrollView= (NestedScrollView) findViewById(R.id.rvToDoList);
    mCollapsableLayout.setExpandedTitleTextAppearance(R.style.ExpandedTitleTextAppearence);
    mCollapsableLayout.setCollapsedTitleTextColor(getResources().getColor(R.color.textColor));
    NavigationDrawerActivity drawerFragment= (NavigationDrawerActivity) getSupportFragmentManager().
            findFragmentById(R.id.navigation_drawer);
        drawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawerlayout), toolbar);


}
@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_invento, menu);
    return true;
}

@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.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}
我的
导航抽屉.java1

package com.defcomm.invento;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle; 
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.support.design.widget.CollapsingToolbarLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;
公共类NavigationDrawerActivity扩展片段实现MyAdapter.clickListener{

private ActionBarDrawerToggle mdrawerToggle;
private DrawerLayout mdrawerLayout;
private boolean mUserLearnedState;
private MyAdapter adapter;
private CoordinatorLayout mcoordinator;
private RecyclerView recyclerView;
private CollapsingToolbarLayout collapsingToolbarLayout;
View containerId;
public static final String file_pref_name = "Testpef";
public static final String KEY_USER_VALUE = "user_learned_drawer";
private boolean mfromSavedInstanceState;

public NavigationDrawerActivity() {
    // Required empty public constructor
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedState = Boolean.valueOf(readPreference(getActivity(), KEY_USER_VALUE, "false"));
    if (savedInstanceState != null) {
        mfromSavedInstanceState = true;
    }

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View layout=inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
    recyclerView= (RecyclerView) layout.findViewById(R.id.recycler);
    adapter=new MyAdapter(getActivity(),getdata());
    adapter.setClicklistener(this);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    return layout;

}
public static List<ListItems> getdata(){
    List<ListItems> nav_data=new ArrayList<>();
    int[] icons={R.drawable.variable,R.drawable.ignore};
    String[] texts={"Coding","Hacking"};
    for(int i=0;i<icons.length&&i<icons.length;i++){
        ListItems current=new ListItems();
        current.iconId=icons[i];
        current.IconName=texts[i];
        nav_data.add(current);
    }
    return nav_data;
}

public void setUp(final int fragmentId, DrawerLayout drawerlayout, final Toolbar toolbar) {
    mdrawerLayout = drawerlayout;
    containerId = getActivity().findViewById(fragmentId);
    mdrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerlayout, toolbar,
            R.string.drawer_open, R.string.drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!mUserLearnedState) {
                mUserLearnedState = true;
                saveToPreference(getActivity(), KEY_USER_VALUE, mUserLearnedState + "");
            }
            getActivity().invalidateOptionsMenu();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            getActivity().invalidateOptionsMenu();

        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            if (slideOffset < 0.5f) {
                toolbar.setAlpha(1 - slideOffset);
            }
        }
    };
    if (!mUserLearnedState && !mfromSavedInstanceState) {
        mdrawerLayout.openDrawer(containerId);
    }

    mdrawerLayout.setDrawerListener(mdrawerToggle);
    mdrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mdrawerToggle.syncState();

        }
    });

}


public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
    SharedPreferences shared = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = shared.edit();
    editor.putString(preferenceName, preferenceValue);
    editor.apply();
}

public static String readPreference(Context context, String preferenceName, String defaultValue) {
    SharedPreferences share = context.getSharedPreferences(file_pref_name, Context.MODE_PRIVATE);
    return share.getString(preferenceName, defaultValue);
}

@Override
public void ItemCLick(View view, int position) {
    if(position==0){
        startActivity(new Intent(getActivity(),Coding.class));
    }
    if(position==1){
        startActivity(new Intent(getActivity(),Hacking.class));
    }

  }
}
你可以试试这个

@Override
public void onBackPressed() {

    startActivity(new Intent(this,MainActivity.class));
    this.finish();
}
试试这个

Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);

这将关闭所有其他活动并启动MainActivity

这将在抽屉打开并按下back时关闭抽屉,而不是将您带回上一个活动(或退出)


您至少可以检查您的MainActivity是否设置为从NavigationDrawer启动的其他活动的父活动。请参阅。并可能在此处发布您的AndroidManifest.xml,以及它可能与问题相关的其他内容。您是否已重写onBackPressed()在其他活动中?如果是,如何设置?最后你是指底部的后退按钮还是操作栏中的后退按钮?后退按钮是指手机的物理按钮。由于我是android新手,我想知道如何将主活动设置为其他活动的父活动。对于
AndroidManifest.xml
我正在编辑我猜您的代码会添加一个空片段(或活动)返回堆栈。可能你在应用程序启动时看不到这一点,因为你正在加载片段或另一个活动,这是在某个
生命周期方法上进行的。但当你返回时,你会看到它。另外,请将
导航抽屉活动重命名为
导航抽屉片段,因为它是一个片段,而不是一个活动。这对是我,但是有什么理由我们必须这样做吗?它不应该自动设置为启动父活动吗?
Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
DrawerLayout drawer...

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub

    if(drawer.isDrawerOpen(Gravity.LEFT)){
        drawer.closeDrawer(Gravity.LEFT);
    startActivity(new Intent(CurrentActivity.this , MainActivity.class))
    finish();

    }else{
        super.onBackPressed();
    }
}