android - 如何更改片段中单个视图的样式
问题描述
目标:我试图在一个片段中应用两个不同的主题。一个用于片段的整体 xml,另一个用于该片段 xml 中的特定视图。
原因/问题:原因是似乎无法使用 MaterialComponents 将浮动操作按钮的整个背景更改为矢量,但它确实适用于 appCompat。
最初,我尝试使用 style="..." 更改 xml 中的主题,如下所示,但它似乎恢复到清单中声明的主题 AppTheme1。我知道这一点,因为我通过切换那里声明的主题对其进行了测试。也就是说,当我将它切换到 AppTheme2 时,向量在 FAB 中正确加载,但由于我在整个应用程序中都有 MaterialComponents,它在其他地方崩溃了。
解决方案:我认为明显的解决方案是更改相关浮动操作按钮的主题,但我不知道该怎么做。非常感谢任何帮助。谢谢!
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/nationality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:scaleType="fitXY"
app:srcCompat="@drawable/flag_united_states_of_america"
app:borderWidth="0dp"
style="@style/AppTheme2"
app:maxImageSize="56dp" />
主题:
<style name="AppTheme1" parent="Theme.MaterialComponents.Light.NoActionBar" >
&&
<style name="AppTheme2" parent="Theme.AppCompat.Light.NoActionBar" >
使用 MaterialComponents:
使用 AppCompat:
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fabtest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
因此,当主题从 AppCompat 更改为 Material Components 时,图像资源不再正确应用于 Floating Action Button。所以我只想将 AppCompat 应用于浮动操作按钮,但将材质组件保持为主要样式。
解决方案
Ben P. 和 Gabrielle 都是半正确的。答案需要通过以下方式改变主题:
android:theme="@style/SecondTheme"
并将色调设置为null:
app:tint="@null"
在这种情况下,两者都是必需的
总之,给定两个主题,如果您想将其整个背景更改为矢量,而您的主要主题是应用程序清单中引用的 MaterialComponents,那么这是 FloatingActionButton 的正确 XML:
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
app:borderWidth="0dp"
app:srcCompat="@drawable/your_vector"
app:tint="@null"
android:theme="@style/SecondTheme"
app:maxImageSize="56dp" />
感谢加布里埃尔和本的帮助!
推荐阅读
- python - 如何限制 python 模块安装在特定版本的 Python 中?
- node.js - 批量检索 AWS ssm 参数
- python - 通过 WXnotebook 中的选项卡自动切换
- algorithm - 算法的“数学/经验验证”是什么意思?
- amazon-web-services - Cognito 组的 IAM 策略变量
- php - 通过ajax发送数组到php
- html - 访问表格中的嵌套元素并更改html CSS中表格单元格的高度
- r - 通过 gganimate 和 ggforce 移动平面缩放的动画情节?
- vue.js - 将“默认”图像添加到我的(VUE)
- java - 迭代合并排序似乎不正确 - 产生有效的输出