Android onKeyDown回到主要活动

时间:2016-01-26 02:45:22

标签: android fragment exit drawer

我是Android新手。我想开发一个从片段回到主屏幕到退出应用程序的功能,但它不起作用。目前,一旦我按下后退按钮,它将提示退出应用程序。如何返回主活动以从onKeyDown退出应用程序?

 public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, FragmentFlickrGridImage.OnFragmentInteractionListener
     {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (savedInstanceState == null) {
        Fragment fragment = null;
        Class fragmentClass = null;
        fragment = new MyFragment("0");
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }


    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.setItemIconTintList(null);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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 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.share) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    Class fragmentClass = null;
    String title="";

    if (id == R.id.one) {
        fragment = new MyFragment("1");
        title="One";
    } else if (id == R.id.two) {
        fragment = new MyFragment("2");
        title ="two";
    } else if (id == R.id.three) {
        fragment = new MyFragment("3");
        title="three";
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    getSupportActionBar().setTitle(title);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onFragmentInteraction(Uri uri) {

}
// confirm when user click back key
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode != KeyEvent.KEYCODE_BACK)  return super.onKeyDown(keyCode, event);

    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    //Yes button clicked
                    finish();
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    break;
            }
        }
    };

    AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setMessage("Are you sure?")
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener)
            .setCancelable(false)
            .setTitle("Exit");
    builder.show();

    return super.onKeyDown(keyCode, event);
} 

下面是我在实现addtobackstack

时得到的错误代码
Application is not responding: AppWindowToken{bcc0a65 token=Token{1a7f775c ActivityRecord{3ccf31cf u0 com.google.android.googlequicksearchbox/com.google.android.launcher.GEL t310}}}.  It has been 5010.0ms since event, 5010.0ms since wait started.  
Reason: Waiting because no window has focus but there is a focused application that may eventually add a window when it finishes starting up. 

3 个答案:

答案 0 :(得分:0)

替换片段时添加fragmentManager.addToBackStack(null);

    FragmentManager fragmentManager = getSupportFragmentManager(); 
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment);
    fragmentManager.addToBackStack(null);
    fragmentManager.commit();

通过调用addToBackStack(),替换事务将保存到后台,因此用户可以通过按“返回”按钮来反转事务并恢复上一个片段。

onBackPressed()

旁边的主要活动/主页活动中
    public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
     // Add your Dialogue or whatever to alert 
       moveTaskToBack(true);
      }
      return super.onKeyDown(keyCode, event);
     }

     @Override
     public void onBackPressed() {

      super.onBackPressed();
      onKeyDown(KeyEvent.KEYCODE_BACK, null);
     }

答案 1 :(得分:0)

以下是我的解决方案

定义名为backstact_count的变量以保存已替换fragments的数量。

当您用另一个替换时,您需要将当前fragment添加到backstack

public void replaceFragment(Fragment fragment, boolean isAddToBackStack) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.flContent, fragment);
    if (isAddToBackStack) {
        transaction.addToBackStack(fragment.getClass().toString());
        backstack_count ++;
    }
    transaction.commit();
}

然后覆盖onBackPressed()

@Override
    public void onBackPressed() {
if (backstack_count > 0) {
            FragmentManager manager = getSupportFragmentManager();
            manager.popBackStack();
            backstack_count--;
        } else {
           super.onBackPressed();
        }
    }

最后,在onCreate()中编辑替换的片段,如下所示:

replaceFragment(fragment, true);

答案 2 :(得分:0)

尝试在onBackPressed方法中调用moveTaskToBack(true)。包装逻辑以检查片段是否是您要从此方法周围退出的片段。看看我在这个问题上的答案:

Switch between Fragments with onNavigationItemSelected in new Navigation Drawer Activity template (Android Studio 1.4 onward)