如何在打开的活动的动作栏中向片段添加后退按钮? [英] How to add a back button to the fragment in the action bar of an opened activity?

查看:61
本文介绍了如何在打开的活动的动作栏中向片段添加后退按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 HomeActivity ,它实现了 NavigationView ,而没有ToolBar (带有ActionBar).在本活动中,我实现了用于导航到 SettingsFragment :

onNavigationItemSelected .

 受保护的void onCreate(捆绑保存的InstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_menu);ActionBar actionBar = getSupportActionBar();如果(actionBar!= null){actionBar.setDisplayHomeAsUpEnabled(true);actionBar.setHomeButtonEnabled(true);}//更多代码getSupportFragmentManager().beginTransaction().replace(R.id.container,new DashboardActivity()).commit();}@Overridepublic boolean onNavigationItemSelected(@NonNull MenuItem item){//更多代码getSupportFragmentManager().beginTransaction().replace(R.id.container,new SettingsFragment()).commit();} 

SettingsFragment 片段中,我有一个侦听器来打开新活动:

  @Override公共视图onCreateView(LayoutInflater充气器,ViewGroup容器,捆绑的saveInstanceState){fragmentView = inflater.inflate(R.layout.activity_settings,container,false);FloatingActionButton fab =(FloatingActionButton)fragmentView.findViewById(R.id.myfab);fab.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){Intent intent = new Intent(getActivity(),SubSettingsActivity.class);fragmentView.getContext().startActivity(intent);startActivity(intent);}});返回fragmentView;} 

它打开一个活动,但没有上一个片段的后退按钮.在操作栏中添加此按钮的正确方法是什么?

编辑:我希望按钮返回到上一个片段 SettingsFragment ,而不是保存片段的活动.为什么实施 NavigationView 如此困难?

解决方案

您的SubSettingsActivity主题应该扩展 Theme.AppCompat.Light.DarkActionBar
然后在Java中执行onCreate

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

然后在AndroidManifest中,您声明SubSettingsActivity做:

android:parentActivity ="YOUR_ACTIVITY"

YOUR_ACTIVITY是保存片段的活动

修改:如果您想导航回SettingFragment,最好使用Android Jetpack导航组件.它让您似乎使用片段.链接在这里:

请注意资源类型,您必须选择导航

步骤3::由于已创建片段,请转到保存您的片段的活动xml,例如activity_main.xml添加以下内容:

 <片段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 是将处理您的片段的类, navGraph 将是您先前创建的导航文件.

第4步::将片段添加到导航文件,打开在第2步中创建的导航文件,将标签切换为设计.如下图所示

注意,您的将是空的.使用加号(屏幕截图中的1)将片段添加到设计视图中.请注意(屏幕截图中的2)起始片段,该片段将首先膨胀.表示当您打开MainActivity时,它在导航图中的起始片段将是可见的.

卷曲箭头是操作或导航.例如,在我的屏幕快照中,起始片段转到注册片段和登录片段,这仅表示起始片段可以导航到图形内的片段中.如果未在导航图中定义,则不会导航.换句话说,嘿,我将来会想从启动片段导航到注册片段或登录片段,请注意!

第5步::当您要从图形中的片段导航到片段时,实例化NavController的实例:

 私有NavController控制器;@Override公共无效onViewCreated(@NonNull视图视图,@Nullable捆绑包savedInstanceState){super.onViewCreated(view,savedInstanceState);控制器= Navigation.findNavController(view);} 

NavController 将允许您导航,我通常在ViewViewd()上实例化它.

然后:

  button.setOnClickListener(new View.OnClickListener(){@Override公共无效onClick(查看){controller.navigate(R.id.action_startFragment_to_anotherFragment);}}); 

要使用片段设置操作栏,请将以下代码放入主机活动的onCreate()中:

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

也在主持人活动中:

  @Overridepublic boolean onSupportNavigateUp(){返回mNavigationController.navigateUp();}@Override公共无效onBackPressed(){super.onBackPressed();} 

查看该视频以了解更多

I have a HomeActivity that implements NavigationView without ToolBar (with ActionBar). In this activity I implement the onNavigationItemSelected that I use to navigate to SettingsFragment:

    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:

    @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. Why implementing NavigationView is so hard?

解决方案

Your SubSettingsActivity's theme should extend Theme.AppCompat.Light.DarkActionBar
Then in java do in onCreate

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

Then in AndroidManifest where u declare SubSettingsActivity do:

android:parentActivity="YOUR_ACTIVITY"

YOUR_ACTIVITY is the activity that holds fragment

Edit: If you wanna navigate back to the SettingFragment its better you use Android Jetpack navigation component. It let's you seemlessly use fragments. Here is the link: https://developer.android.com/guide/navigation/navigation-migrate

How to implement Navigation Component :the simple way

Step 1: Add the required dependencies

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:

Note the Resource type, you must pick Navigation

Step 3: Since your fragments have been created, goto the activity xml that holds your fragment e.g activity_main.xml add the following:

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

Step 4: add your fragments to the navigation file, open your navigation file u created in step 2, switch the tab to design. 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. Notice the (2 in the screenshot) start fragment, this the fragment that will be inflated first. Means when u open MainActivity, its the start fragment in the navigation graph that will be visible.

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:

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

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:

      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

这篇关于如何在打开的活动的动作栏中向片段添加后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆