【问题标题】:Material Button Toggle Group not visible材质按钮切换组不可见
【发布时间】:2021-06-07 04:56:21
【问题描述】:

我正在尝试在现有应用程序中使用Material toggle group

我发现它只有在应用程序使用 Material 组件主题时才有效(可见)。

由于现有应用程序正在使用 Theme.AppCompat.Light,我无法将应用程序主题更改为 Material 组件。

我尝试将“ThemeOverlay.MaterialComponents”用于切换组,但它不起作用。

我也没有找到太多关于主题和覆盖主题的文档。

(编辑)代码预览

在设计工具栏或styles.xml 中将主题更改为Material components 后。

【问题讨论】:

    标签: android android-layout material-components-android android-togglebutton


    【解决方案1】:

    如果您无法将主题更改为从 Material Components 主题继承,您可以从继承自 AppCompat 主题的 Material Components Bridge 主题继承,但也可以定义新的 Material Components 主题属性:

    <style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.Bridge">
    
        <item name="colorPrimary">@color/....</item>
        <item name="colorPrimaryDark">@color/.....</item>
        <!-- ... -->
        
    </style>
    

    【讨论】:

    • @mohammedahmedahmed “不工作”是什么意思?
    • 将应用程序主题的父级更改为“Material Components Bridge”后,切换组仍然不可见。
    • @mohammedahmedahmed 刚刚尝试使用 1.3.0 没有任何问题
    • 我也在使用 1.3.0。我创建了一个快速应用程序并添加了代码快照。
    【解决方案2】:

    首先在 style.xml 中创建你的主题

    <style name="Material" parent="Theme.MaterialComponents.*">
    <!-- Add attributes here -->
    </style>
    

    并将其添加到您正在使用材料组件的活动的清单中

    <manifest 
      <activity
       android:name=".Activity"
       android:theme="@style/Material" />
    </manifest>
    

    如果要为 Fragment 设置 Theme,在 Fragment 的 onCreateView() 中添加下一段代码:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
        // create ContextThemeWrapper from the original Activity Context with the custom theme
        final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.yourCustomTheme);
    
        // clone the inflater using the ContextThemeWrapper
        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);
    
        // inflate the layout using the cloned inflater, not default inflater
        return localInflater.inflate(R.layout.yourLayout, container, false);
    

    【讨论】:

    • 这将改变整个应用程序的主题。在这种情况下这是不可能的。
    • 这只会改变活动的主题,而不是整个应用程序,你必须在活动标签而不是应用程序标签中声明这种风格
    • 你说得对,但这是一个带有片段的活动应用程序。
    • 尝试使用本地充气机,我使用“R.style.Theme_MaterialComponents”作为 ContextThemeWrapper。有了这个,我看到主题改变了,但“切换组”仍然不可见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 2021-11-24
    相关资源
    最近更新 更多