简体   繁体   English

在片段中隐藏或显示操作栏 Kotlin

[英]Hide or Show Action Bar in Fragments Kotlin

I have to know the best way to deal with hiding or show Action Bar in Fragments.我必须知道处理在片段中隐藏或显示操作栏的最佳方法。 I figured out that it, not the same as in Activity where I could apply the style in Manifest.我发现它与 Activity 中的不同,我可以在 Manifest 中应用样式。 I have tried to apply the style in the Fragment XML file with no effect.我试图在 Fragment XML 文件中应用该样式,但没有任何效果。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PreviewFragment"
    **style="@style/MyStyleHereNoActionBar"**>
</FrameLayout>

Another option that worked, but might be unstable is:另一个有效但可能不稳定的选项是:

class PreviewFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment

// hide action bar         (requireActivity() as AppCompatActivity).supportActionBar?.hide()
// show action bar         (requireActivity() as AppCompatActivity).supportActionBar?.show()

        return inflater.inflate(R.layout.fragment_preview, container, false)
    }

and the last one adding one or both methods:最后一个添加一种或两种方法:

override fun onResume() {
        super.onResume()
        (activity as AppCompatActivity?)!!.supportActionBar!!.hide()
    }

    override fun onStop() {
        super.onStop()
        (activity as AppCompatActivity?)!!.supportActionBar!!.show()
    }

So I love to know what I could do better or another way of doing it.所以我很想知道我可以做的更好或其他方式。 Or rather a right way to do it.或者说是正确的方法。

And second how to apply custom styles to Fragments the right way.其次如何以正确的方式将自定义 styles 应用于 Fragments。

Thank you.谢谢你。

You are adding fragments inside an activity and the activity has action bar.您在活动中添加片段并且活动具有操作栏。 So in the specific fragment where you want to show the action bar get the activity and show the activity, and hide it where you don't want to show.因此,在您要显示操作栏的特定片段中,获取活动并显示活动,并将其隐藏在您不想显示的地方。

Or if you want to use action bar inside a fragment then just add a linear layout to the top of the fragment with height "?android:attr/actionBarSize" .或者,如果您想在片段中使用操作栏,则只需在片段顶部添加一个线性布局,高度为"?android:attr/actionBarSize" I think this should do the job.我认为这应该可以完成这项工作。

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

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