【问题标题】:Hide or Show Action Bar in Fragments Kotlin在 Fragments Kotlin 中隐藏或显示操作栏
【发布时间】:2021-04-08 07:22:06
【问题描述】:

我必须知道处理在片段中隐藏或显示操作栏的最佳方法。我发现它与 Activity 中的不同,我可以在 Manifest 中应用样式。 我尝试在 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>

另一个可行但可能不稳定的选项是:

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

最后一个添加一种或两种方法:

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

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

所以我很想知道我可以做得更好或以其他方式做到这一点。或者说是正确的方法。

其次,如何以正确的方式将自定义样式应用于 Fragments。

谢谢。

【问题讨论】:

  • 我没有遇到这种方法的任何问题,ActionBar 是活动的一部分而不是片段,因此您可以通过其活动访问它
  • 仅供参考,您可以使用NoActionBar 主题,然后在需要的片段布局中放置一个工具栏视图。您可以直接管理 Toolbar,也可以将其设置为 Activity 的支持操作栏,以传统方式对其进行管理。如果这样做,请在离开片段时取消支持操作栏。 developer.android.com/reference/androidx/appcompat/app/…

标签: android kotlin android-actionbar hide show


【解决方案1】:

您在活动中添加片段并且活动具有操作栏。因此,在您要显示操作栏的特定片段中获取活动并显示活动,并将其隐藏在您不想显示的地方。

或者,如果您想在片段中使用操作栏,则只需在片段顶部添加一个线性布局,高度为"?android:attr/actionBarSize"。我认为这应该可以完成这项工作。

【讨论】:

  • 我明白了,关于决定 Fragments UI 外观的活动。不容易处理变化。
  • 我从未尝试过使用操作栏。但在一个项目中,我想为片段更改的操作栏设置动画。所以我只使用了一个活动,而其他只使用了片段,并在主要活动中使用了线性布局作为操作栏。因此,当片段更改发生时,它会调用 animateActionBar 函数,它对我来说工作得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多