动作栏后退按钮不工作

时间:2022-08-23 23:36:25

with the help of these Android Docs.I am trying to do a action bar Back button.I get an Action Bar Back Button like these below image:

在这些Android文档的帮助下。我想做一个动作栏后退按钮。我得到了一个动作栏后退按钮,如下图所示:

动作栏后退按钮不工作

Output:

输出:

But My problem is After watching the Gallery images I press the action bar back button.

但我的问题是看完画廊的图片后,我按下动作栏后退按钮。

Then it is not working.But it have to go back to previous page.

那么它就不起作用了。但它必须回到上一页。

Listed below are the codings.

下面列出了编码。

GalleryActivity.java:

GalleryActivity.java:

    import android.app.ActionBar;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.app.NavUtils;
    import android.view.MenuItem;

    import com.fth.android.R;

   public class GalleryActivity extends FragmentActivity {

    private int position;
    private static String id;
    private static String name;
    private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
    private ViewPager mViewPager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_gallery);

            position = getIntent().getExtras().getInt("position");

            id = getIntent().getExtras().getString("id");

            name = getIntent().getExtras().getString("name");

            mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());

            // Set up action bar.
            final ActionBar actionBar = getActionBar();


            actionBar.setDisplayHomeAsUpEnabled(true);

           // getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|ActionBar.DISPLAY_HOME_AS_UP);

            // Set up the ViewPager, attaching the adapter.
            mViewPager = (ViewPager) findViewById(R.id.pager);
            mViewPager.setAdapter(mDemoCollectionPagerAdapter);
        }

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

                    Intent upIntent = new Intent(this, HomeActivity.class);
                    upIntent.putExtra("position", position);
                    if (NavUtils.shouldUpRecreateTask(this, upIntent)) {

                        TaskStackBuilder.from(this)
                                .addNextIntent(upIntent)
                                .startActivities();
                        finish();
                    } else {

                        NavUtils.navigateUpTo(this, upIntent);
                    }
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }


      }

GalleryDetailFragment.java:

GalleryDetailFragment.java:

import com.sit.fth.model.GalleryDetail;
import com.sit.fth.util.APIServiceHandler;
import com.sit.fth.util.AppConstants;
import com.sit.fth.util.AppPromoPager;

public class GalleryDetailFragment extends BaseFragment implements
        PromoPagerListener {


    private TextView countView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        this.setHasOptionsMenu(true);
        id = getArguments().getString("id");
        name = getArguments().getString("name");
        View view = inflater.inflate(R.layout.app_pager, null);



        return view;
    }

}

Anybody can help me if you know how to solve these.Thank You.

如果你知道如何解决这些问题,任何人都可以帮助我。谢谢你!

10 个解决方案

#1


124  

I solved these problem by adding the below coding in GalleryActivity.

我通过在GalleryActivity中添加下面的代码来解决这些问题。

ActionBar actionBar;
actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

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

    return super.onOptionsItemSelected(item);
}

In MainActivity:

在MainActivity:

Previously,

在此之前,

public class HomeActivity extends BaseActivity

公共类的HomeActivity扩展了BaseActivity。

Then I change into

然后我改变成

public class HomeActivity extends FragmentActivity

公共班级的家庭活动扩展了碎片活动

In GalleryFragment:

在GalleryFragment:

I use Intent to pass it to the GalleryActivity.

我用意图把它传递给画廊活动。

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);

        Intent intent = new Intent(getActivity(), GalleryActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("id", gallery.getGalId());
        intent.putExtra("name", gallery.getAlbumTitle());
        startActivity(intent);

        // mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
    } 

#2


26  

Please read this

请阅读这

you should have something like this:

你应该有这样的东西:

    <activity
        android:name="com.sit.fth.activity.HomeActivity"
        android:screenOrientation="portrait">

    </activity>
    <activity
        android:name="com.sit.fth.activity.GalleryActivity"
        android:screenOrientation="portrait"
        android:parentActivityName="com.sit.fth.activity.HomeActivity">

    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.sit.fth.activity.HomeActivity"/>

   </activity>


then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).

然后调用NavUtils.navigateUpFromSameTask(this)将导致导航到父活动(HomeActivity)。

#3


7  

Try like

试着喜欢

First of all you need to use addToBackStack() before commit() for Fragments

首先,需要在提交()之前对片段使用addToBackStack()

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

#4


0  

None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.

这里提供的答案对我都不起作用。我必须把开关放在onMenuItemSelected方法中。我知道这不是Android文档中所描述的,但是它仍然有效,所以我想我还是把它留给遇到同样问题的人。我的问题涉及到一个活动而不是一个片段,但这应该是差不多的。

class FooActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }

        return false;
    }
}

#5


0  

To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:

对我来说,我必须将mDrawerToggle.setToolbarNavigationClickListener(……)设置为触发后退动作的侦听器。否则什么也不做。ActionBarDrawerToggle的源代码是这样的:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mDrawerIndicatorEnabled) {
      toggle();
    } else if (mToolbarNavigationClickListener != null) {
      mToolbarNavigationClickListener.onClick(v);
    }
  }
});

So the default behaviour is actually to call our listener, and not do any magic on its own.

所以默认的行为实际上是调用我们的监听器,而不使用任何魔法。

#6


0  

onCreate

onCreate

{
    ...
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            resetActionBar();
    ...
 }


public void resetActionBar()
    {
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

 @Override
          public void onBackPressed() {
            FragmentManager fm = getSupportFragmentManager();
            int count = fm.getBackStackEntryCount();
            if(count == 0) {
                // Do you want to close app?
                showDialog();
            }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.
            int id = item.getItemId();
            Log.i("coming", "comming");
            //noinspection SimplifiableIfStatement
            if(id==android.R.id.home){
                if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                    onBackPressed();
                else
                    drawerLayout.openDrawer(navigationView);
                return  true;
            }

            return super.onOptionsItemSelected(item);
        }

#7


0  

Here is one more thing to check for in case the other answers here (or here or here or here) don't work.

这里还有一件事要检查,以防这里(这里或这里或这里)的其他答案无效。

I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.

我从另一个禁用菜单的活动中复制了一些代码。删除这个方法(并应用其他答案中给出的解决方案)允许up按钮工作。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // hide the menu
    return false;
}

#8


0  

You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.

您只需将下面一行添加到manifest.xml中的活动。父活动是您想要返回的活动。

    android:parentActivityName=".activities.MainActivity"

#9


0  

Use on SupportNavigateUp() method and call onBackPressed in this method.

使用SupportNavigateUp()方法并在此方法中调用onBackPressed。

#10


0  

In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.

在我的例子中,我重写了onCreateOptionsMenu方法,我忘记了在最后调用super。

#1


124  

I solved these problem by adding the below coding in GalleryActivity.

我通过在GalleryActivity中添加下面的代码来解决这些问题。

ActionBar actionBar;
actionBar=getActionBar();

actionBar.setDisplayHomeAsUpEnabled(true);

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

    return super.onOptionsItemSelected(item);
}

In MainActivity:

在MainActivity:

Previously,

在此之前,

public class HomeActivity extends BaseActivity

公共类的HomeActivity扩展了BaseActivity。

Then I change into

然后我改变成

public class HomeActivity extends FragmentActivity

公共班级的家庭活动扩展了碎片活动

In GalleryFragment:

在GalleryFragment:

I use Intent to pass it to the GalleryActivity.

我用意图把它传递给画廊活动。

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);

        Intent intent = new Intent(getActivity(), GalleryActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("id", gallery.getGalId());
        intent.putExtra("name", gallery.getAlbumTitle());
        startActivity(intent);

        // mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
    } 

#2


26  

Please read this

请阅读这

you should have something like this:

你应该有这样的东西:

    <activity
        android:name="com.sit.fth.activity.HomeActivity"
        android:screenOrientation="portrait">

    </activity>
    <activity
        android:name="com.sit.fth.activity.GalleryActivity"
        android:screenOrientation="portrait"
        android:parentActivityName="com.sit.fth.activity.HomeActivity">

    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.sit.fth.activity.HomeActivity"/>

   </activity>


then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).

然后调用NavUtils.navigateUpFromSameTask(this)将导致导航到父活动(HomeActivity)。

#3


7  

Try like

试着喜欢

First of all you need to use addToBackStack() before commit() for Fragments

首先,需要在提交()之前对片段使用addToBackStack()

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

#4


0  

None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.

这里提供的答案对我都不起作用。我必须把开关放在onMenuItemSelected方法中。我知道这不是Android文档中所描述的,但是它仍然有效,所以我想我还是把它留给遇到同样问题的人。我的问题涉及到一个活动而不是一个片段,但这应该是差不多的。

class FooActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ...

        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }

        return false;
    }
}

#5


0  

To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:

对我来说,我必须将mDrawerToggle.setToolbarNavigationClickListener(……)设置为触发后退动作的侦听器。否则什么也不做。ActionBarDrawerToggle的源代码是这样的:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    if (mDrawerIndicatorEnabled) {
      toggle();
    } else if (mToolbarNavigationClickListener != null) {
      mToolbarNavigationClickListener.onClick(v);
    }
  }
});

So the default behaviour is actually to call our listener, and not do any magic on its own.

所以默认的行为实际上是调用我们的监听器,而不使用任何魔法。

#6


0  

onCreate

onCreate

{
    ...
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            resetActionBar();
    ...
 }


public void resetActionBar()
    {
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

 @Override
          public void onBackPressed() {
            FragmentManager fm = getSupportFragmentManager();
            int count = fm.getBackStackEntryCount();
            if(count == 0) {
                // Do you want to close app?
                showDialog();
            }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.
            int id = item.getItemId();
            Log.i("coming", "comming");
            //noinspection SimplifiableIfStatement
            if(id==android.R.id.home){
                if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                    onBackPressed();
                else
                    drawerLayout.openDrawer(navigationView);
                return  true;
            }

            return super.onOptionsItemSelected(item);
        }

#7


0  

Here is one more thing to check for in case the other answers here (or here or here or here) don't work.

这里还有一件事要检查,以防这里(这里或这里或这里)的其他答案无效。

I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.

我从另一个禁用菜单的活动中复制了一些代码。删除这个方法(并应用其他答案中给出的解决方案)允许up按钮工作。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // hide the menu
    return false;
}

#8


0  

You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.

您只需将下面一行添加到manifest.xml中的活动。父活动是您想要返回的活动。

    android:parentActivityName=".activities.MainActivity"

#9


0  

Use on SupportNavigateUp() method and call onBackPressed in this method.

使用SupportNavigateUp()方法并在此方法中调用onBackPressed。

#10


0  

In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.

在我的例子中,我重写了onCreateOptionsMenu方法,我忘记了在最后调用super。