Java 将工具栏与片段一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29020935/
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-11 07:12:33  来源:igfitidea点击:

Using Toolbar with Fragments

javaandroidandroid-fragmentsandroid-viewpagerandroid-toolbar

提问by Al Hennessey

I am trying to create a viewpager that swipes through 3 different fragments each with a different toolbar. I have implemented the new toolbar in an activity before and got it to work however I am trying to get it to work with fragments

我正在尝试创建一个 viewpager,它可以浏览 3 个不同的片段,每个片段都有不同的工具栏。我之前在一个活动中实现了新的工具栏并让它工作但是我试图让它与片段一起工作

Here is the fragment code

这是片段代码

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout resource that'll be returned
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);


    mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_home);
    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
    }
    mToolbar.setTitle(null);

    return rootView;
}

I am extending my fragment with Fragment, however I am getting the error

我正在用 扩展我的片段Fragment,但是我收到了错误

Cannot resolve method setSupportActionBar

I am not sure how to resolve this, if I remove the setSupportActionBarcode will it stop working with certain devices?

我不知道如何解决这个问题,如果我删除setSupportActionBar代码,它会停止在某些设备上工作吗?

采纳答案by vinitius

Fragmentsdon't have such method setSupportActionBar(). ActionBar is a property of Activity, so to set your toolbar as the actionBar, your activity should extend from ActionBarActivity and then you can call in your Fragment:

片段没有这种方法setSupportActionBar()。ActionBar 是 Activity 的一个属性,因此要将您的工具栏设置为 actionBar,您的 Activity 应从 ActionBarActivity 扩展,然后您可以在您的 Fragment 中调用:

 ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar);

UPDATE

更新

If you're using AppCompatActivity:

如果您使用AppCompatActivity

 ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);

回答by muruthi

With the new AppCompatActivity you should call it instead of ActionBarActivity:

使用新的 AppCompatActivity,您应该调用它而不是 ActionBarActivity:

((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

回答by H.T

You can add toolbar in Fragments using this

您可以使用此在 Fragments 中添加工具栏

 ((YOUR_ACTIVITY) getActivity()).getDelegate().setSupportActionBar(toolbar);

回答by Faisal Naseer

I have seen a lot of answers mentioning to setSupportActionBarfor toolbar inside Fragmentbut this approach may go wrong if you are having a a toolbar in Activityand a separate Toolbarin Fragment.

我见过很多答案一提到的setSupportActionBar工具栏里面Fragment,但如果你有在AA工具栏这种做法可能出错Activity和独立ToolbarFragment

  1. As you shift setSupportActionBarfrom Activity's Toolbar to Fragment's toolbar, You may face duplication of MenuItemeven you try to override using setHasOptionsMenu(true).
  2. Secondly If you want to update Activity's Toolbar you see your changes are not reflected because of setSupportActionBarinside your Fragment.
  1. 当您setSupportActionBar从 Activity 的工具栏切换到 Fragment 的工具栏时,MenuItem即使您尝试使用setHasOptionsMenu(true).
  2. 其次,如果您想更新 Activity 的工具栏,您会看到您的更改未反映setSupportActionBar在您的 Fragment 内部。

So in order to avoid this I recommend to use toolbar methods like this inside fragment to inflate menu and use

所以为了避免这种情况,我建议在片段内部使用这样的工具栏方法来膨胀菜单并使用

 toolbar = (Toolbar) view.findViewById(R.id.toolbar_frag);
    toolbar.inflateMenu(R.menu.frag_menu_items);
    Menu menu = toolbar.getMenu();

and use Toolbar.OnMenuItemClickListenerinterface to receive with menuItems click events.

并使用Toolbar.OnMenuItemClickListener接口来接收菜单项单击事件。

Edit(Section Copied from MrEngineer13 answer)

编辑(从MrEngineer13 回答复制的部分

and if you are worried about the back button you can set it like this

如果你担心后退按钮,你可以这样设置

toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       //What to do on back clicked
   }
});

回答by Phan Van Linh

Base on @Faisal Naseer answer. Here is the full example (with few notes) for using custom Toolbarwith navigationand menuin Fragment

基于@Faisal Naseer 的回答。下面是完整的例子(有几个注意事项)使用自定义的Toolbar具有导航菜单Fragment

fragment_home.xml

fragment_home.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"">

    ...
    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar_home"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:title="Home" /> 

</androidx.constraintlayout.widget.ConstraintLayout>

HomeFragment.kt

HomeFragment.kt

class HomeFragment : BaseFragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        // setHasOptionsMenu(true): don't need this anymore
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        toolbar_home.setNavigationIcon(R.drawable.ic_back) // need to set the icon here to have a navigation icon. You can simple create an vector image by "Vector Asset" and using here
        toolbar_home.setNavigationOnClickListener {
            // do something when click navigation
        }

        toolbar_home.inflateMenu(R.menu.menu_home)
        toolbar_home.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.action_add -> {
                    // do something
                    true
                }
                R.id.action_update -> {
                    // do something
                    true
                }
                else -> {
                    super.onOptionsItemSelected(it)
                }
            }
        }
    }
}

menu_home.xml

menu_home.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_add"
        android:title="@string/add_device"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_update_room"
        android:title="@string/update_room"
        app:showAsAction="never" />

</menu>

Hope it help

希望有帮助

enter image description here

在此处输入图片说明