材质按钮切换组不可见

时间:2021-03-09 09:53:27

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

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

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

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

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

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

(编辑)代码预览enter image description here

在设计工具栏或styles.xml 中将主题更改为Material 组件后。 enter image description here

2 个答案:

答案 0 :(得分:0)

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

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

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

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

如果要为 Fragment 设置主题,请在 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);

答案 1 :(得分:0)

如果您不能将主题更改为继承自 Material Components 主题,您可以继承自 AppCompat 主题的 Material Components Bridge 主题,但也可以定义新的 Material Components 主题属性:< /p>

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.Bridge">

    <item name="colorPrimary">@color/....</item>
    <item name="colorPrimaryDark">@color/.....</item>
    <!-- ... -->
    
</style>