简体   繁体   English

如何在已打开活动的操作栏中向片段添加后退按钮?

[英]How to add a back button to the fragment in the action bar of an opened activity?

I have a HomeActivity that implements NavigationView without ToolBar (with ActionBar).我有一个HomeActivity ,它实现了没有 ToolBarNavigationView (带有 ActionBar)。 In this activity I implement the onNavigationItemSelected that I use to navigate to SettingsFragment :在此活动中,我实现了用于导航到SettingsFragmentonNavigationItemSelected

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        // more code
        getSupportFragmentManager().beginTransaction().replace(R.id.container,new DashboardActivity()).commit();
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // more code
                getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();
    }

In the SettingsFragment fragment I have a listener to open a new activity:SettingsFragment片段中,我有一个监听器来打开一个新活动:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.activity_settings, container, false);
        FloatingActionButton fab = (FloatingActionButton) fragmentView.findViewById(R.id.myfab);
        fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), SubSettingsActivity.class);
                fragmentView.getContext().startActivity(intent);
                startActivity(intent);
            }
        });
        return fragmentView;
    }

It opens an activity but without a back button to the previous fragment.它打开一个活动,但没有返回前一个片段的按钮。 What's the proper way to add this button in the action bar?在操作栏中添加此按钮的正确方法是什么?

EDIT : I would like the button to go back to the previous fragment SettingsFragment and not to the activity that holds the fragments.编辑:我希望 go 的按钮回到上一个片段SettingsFragment而不是保存片段的活动。 Why implementing NavigationView is so hard?为什么实现NavigationView这么难?

Your SubSettingsActivity's theme should extend Theme.AppCompat.Light.DarkActionBar您的 SubSettingsActivity 的主题应该扩展Theme.AppCompat.Light.DarkActionBar
Then in java do in onCreate然后在 java 中做 onCreate

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

Then in AndroidManifest where u declare SubSettingsActivity do:然后在您声明 SubSettingsActivity 的 AndroidManifest 中执行以下操作:

android:parentActivity="YOUR_ACTIVITY"

YOUR_ACTIVITY is the activity that holds fragment YOUR_ACTIVITY 是持有片段的活动

Edit: If you wanna navigate back to the SettingFragment its better you use Android Jetpack navigation component.编辑:如果你想导航回 SettingFragment,最好使用 Android Jetpack 导航组件。 It let's you seemlessly use fragments.它让你无缝地使用碎片。 Here is the link: https://developer.android.com/guide/navigation/navigation-migrate这是链接: https://developer.android.com/guide/navigation/navigation-migrate

How to implement Navigation Component :the simple way如何实现导航组件:简单的方法

Step 1: Add the required dependencies第 1 步:添加所需的依赖项

implementation 'androidx.navigation:navigation-fragment:2.3.0-alpha05'
implementation 'androidx.navigation:navigation-ui:2.3.0-alpha05'

Step 2: Goto res folder on Android Studio, right click it, new > android Resource File Youll see the following dialog:步骤 2:转到 Android Studio 上的 res 文件夹,右键单击它,新建 > android 资源文件 您将看到以下对话框: 见截图

Note the Resource type, you must pick Navigation注意资源类型,您必须选择导航

Step 3: Since your fragments have been created, goto the activity xml that holds your fragment eg activity_main.xml add the following:第 3 步:由于您的片段已创建,请转到包含您的片段的活动 xml,例如 activity_main.xml 添加以下内容:

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/adView"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:defaultNavHost="true"
    app:navGraph="@navigation/main_nav"
    android:id="@+id/nav_host_frag"/>

NavHostFragment is the class that will handle your fragments, navGraph will be your navigation file you created earlier. NavHostFragment是将处理您的片段的 class , navGraph将是您之前创建的导航文件。

Step 4: add your fragments to the navigation file, open your navigation file u created in step 2, switch the tab to design.第 4 步:将您的片段添加到导航文件中,打开您在第 2 步中创建的导航文件,将选项卡切换到设计。 As seen in the image below如下图所示在此处输入图像描述

Note yours will be empty.请注意,您的将是空的。 Use the add sign(1 in the screenshot) to add your fragments to the design view.使用添加符号(屏幕截图中的 1)将您的片段添加到设计视图中。 Notice the (2 in the screenshot) start fragment, this the fragment that will be inflated first.注意(屏幕截图中的 2)开始片段,这是首先膨胀的片段。 Means when u open MainActivity, its the start fragment in the navigation graph that will be visible.意味着当你打开 MainActivity 时,它在导航图中的起始片段将是可见的。

The curly arrows are the actions or navigations.卷曲箭头是操作或导航。 For example, in my screenshot, start fragment goes to signup fragment and login fragment, it simply means where start fragment can navigate to within the fragments inside the graph.例如,在我的屏幕截图中,起始片段转到注册片段和登录片段,它仅表示起始片段可以在图表内的片段中导航到的位置。 if its not defined in the navigation graph, it wont navigate.如果未在导航图中定义,则不会导航。 Other words, hey nav i will want to navigate from splash fragment to signup fragment or login fragment in the future, take note!换句话说,嘿导航我将来会想要从启动片段导航到注册片段或登录片段,请注意!

Step 5: when you want to navigate to a fragment from a fragment within the graph instantiate an instance of NavController:第 5 步:当您想从图中的片段导航到片段时,实例化 NavController 的实例:

     private NavController controller;

     @Override
     public void onViewCreated(@NonNull View view, @Nullable Bundle 
     savedInstanceState) {
       super.onViewCreated(view, savedInstanceState);

        controller = Navigation.findNavController(view);
    }

NavController will let you navigate and i usually instantiate it onViewCreated() NavController将让您导航,我通常将其实例化为 onViewCreated()

then:然后:

button.setOnClickListener(new View.OnClickListener(){
  @Override
   public void onClick(View view){
      controller.navigate(R.id.action_startFragment_to_anotherFragment);
   }
 }); 

To set your actionbar with the fragments, put the following code in onCreate() of host activity:要使用片段设置您的操作栏,请将以下代码放入主机活动的 onCreate() 中:

      NavController mNavigationController = Navigation.findNavController(this,R.id.nav_host_frag);
      NavigationUI.setupActionBarWithNavController(this, mNavigationController);

Also in host activity:同样在主机活动中:

@Override
public boolean onSupportNavigateUp() {
    return mNavigationController.navigateUp();
}

@Override
public void onBackPressed() {
    super.onBackPressed();

}

Check this video for more查看此视频了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM