Android 操作栏后退按钮不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24032956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:44:37  来源:igfitidea点击:

Action bar Back button not working

androidandroid-actionbar

提问by Steve

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 文档的帮助下。我正在尝试做一个动作栏后退按钮。我得到一个动作栏后退按钮,如下图所示:

enter image description here

在此处输入图片说明

Output:

输出:

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

但我的问题是在观看图库图像后,我按下action bar back button.

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

然后it is not working。但它必须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.

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

回答by Steve

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

公共类 HomeActivity 扩展了 FragmentActivity

In GalleryFragment:

GalleryFragment 中:

I use Intentto pass it to the GalleryActivity.

Intent用来将它传递给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());
    } 

回答by x90

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)。

回答by Chanaka Fernando

You need to call setDisplayHomeAsUpEnabled(true)method in the onCreate method and override onSupportNavigateUp()and call onBackPressed()in it as below. That's it. done :)

您需要在 onCreate 方法中调用setDisplayHomeAsUpEnabled(true)方法并覆盖 onSupportNavigateUp()并在其中调用onBackPressed(),如下所示。就是这样。完毕 :)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_help);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

回答by scientist

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"

回答by Amit Gupta

Try like

试试像

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

首先你需要使用addToBackStack()before commit()for Fragments

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

回答by Vaishakh

Best and easy answer is add the parent activity name in Manifest file, so Actionbar back button will work.

最好和简单的答案是在清单文件中添加父活动名称,这样操作栏后退按钮就可以工作了。

For that under that Activity tag of Manifest File use android:parentActivityName=".MyCustomParentActivity"

对于在 Manifest File 的 Activity 标签下使用 android:parentActivityName=".MyCustomParentActivity"

回答by Raj Godara

Use on SupportNavigateUp()method and call onBackPressedin this method.

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

回答by PLPeeters

None of the answers provided here worked for me. I had to put the switchinside the onMenuItemSelectedmethod. 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 Activityinstead of a Fragmentthough, but that should be pretty much the same.

这里提供的答案都不适合我。我不得不把switch里面的onMenuItemSelected方法。我知道这不是 Android 文档中所述的内容,但它仍然有效,所以我只是想我会把它留在这里给遇到同样问题的人。我的问题涉及一个Activity而不是一个Fragment,但这应该几乎相同。

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

回答by daniel.gindi

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 ActionBarDrawerTogglelooks 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.

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

回答by Hamza Mehmood

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