后退按钮退出应用程序而不是返回MainActivity

时间:2017-12-25 05:59:37

标签: java android xml

我有两项活动,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);
    }


}

我错过了什么吗?

5 个答案:

答案 0 :(得分:3)

更改setxkbmap layout方法,如下面的

onBackPressed

您还可以转到@Override public void onBackPressed(){ //remove super.onBackPressed() and you can handle intent to mainActivity or //any other activity } 并在删除manifest.xml

后将活动的父级设置为mainActivity

答案 1 :(得分:2)

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

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

将其删除

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

就够了

并确保在您撰写startActivity(intent)时不要在其后添加finish()

答案 2 :(得分:1)

您的 QuestionsActivity onBackPressed

已有方法

将您的代码放在

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

答案 3 :(得分:1)

足以显示后退按钮

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

在主要活动中使用intent和startActivity

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

答案 4 :(得分:1)

  

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

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

然后回调按钮方法这段代码足以转到上一个活动,否则你可以在onBackPressed方法中使用intent方法返回

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

后退按钮点击功能

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

            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}