How to add a listener for the up button in ActionBar on Android?

让人想犯罪 __ 提交于 2020-01-03 05:24:11

问题


I added the up button in the action bar of my android activity in this way:

Activity:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Manifest:

android:parentActivityName=".MenuActivity">

It work fine but now i want to add a transition effect between activities. This transition work well:

Intent intent = new Intent(getApplicationContext(), MenuActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);

But where i should put this transition code? I dont have any listener for the back button in the action bar.

Thanks in advice guys


回答1:


The up button in the action bar is treated as a menu item with ID android.R.id.home, as you can read in the docs. There you can find that you can handle clicks on it using this code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        // Respond to the action bar's Up/Home button
        return false;
    }
    return super.onOptionsItemSelected(item);
}



回答2:


Add this after the command setSupportActionBar(toolbar);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // your code
        }
    });



回答3:


If you have a back button in your actionbar then you must have defined in your menu.xml file. so we have to add the listener for that button in the java file.

here is how the menu.xml looks like :

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.sknandroidapps.skn.ptternlock.LockScreen">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />

so if you want to add the listener to your action_settings button then you have to do this :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    noinspection SimplifiableIfStatement
       if (id == R.id.action_settings) {
         //here you have to put the transiction code.
         return true;
       }

    return super.onOptionsItemSelected(item);
}

apply this to your code and let me know if it works.



来源:https://stackoverflow.com/questions/37401287/how-to-add-a-listener-for-the-up-button-in-actionbar-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!