如何在按下电话的后退按钮时加载MainActivity

时间:2015-10-06 06:27:11

标签: android back-button

我有一个MainActivity,其中有一个NavigationDrawer。在抽屉的菜单中,每个项目都会开始一个新的活动。现在当我按下任何这些活动的后退按钮时,我最终在一个空白页面,当我再次按下它进入主要活动。我想要的是直接进入主要活动。

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

我的NavigationDrawer.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;

public class NavigationDrawerActivity extends Fragment实现了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));
    }

  }
}

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.defcomm.invento" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".INVENTO"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Coding"
        android:label="@string/title_activity_coding" >
    </activity>
    <activity
        android:name=".Hacking"
        android:label="@string/title_activity_hacking" >
    </activity>
</application>

3 个答案:

答案 0 :(得分:1)

你可以试试这个。

@Override
public void onBackPressed() {

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

答案 1 :(得分:0)

试试这个

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

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

答案 2 :(得分:0)

这会在抽屉打开和关闭时关闭抽屉,而不是将您带回上一个活动(或退出)。

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