irpas技术客

【Android】关于Button中设置背景\样式失效的问题及解决办法_*木易先生*_android button 背景

网络 3926

????????博主最近在学习安卓开发的时候遇到了一个问题,使用Android Studio在为Button设置背景颜色的时候发现设置好后却在运行模拟机上失效了。经过一番查阅资料后才有了正确的解决办法,相信这是很多初学Android开发的朋友都会遇到的一个问题,希望此篇对大家有所帮助。

问题描述:

????????使用Android Studio进行安卓开发时Button的背景色一直无法修改,呈现亮紫色(呈现颜色额和主题有关,我的是亮紫色)。

以其中一个Button举例,代码是这样的:

<Button android:id="@+id/btn_1" android:layout_height="wrap_content" android:layout_width="match_parent" android:text="按钮1" android:textSize="20sp" android:textColor="#0066FF" android:backgroundTint="@null" android:background="#FF0000"/>

正常运行的话第一个Button应该是红色的,但是在模拟机上确实这样:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

问题原因:

????????出现该问题的原因主要是因为使用Android Studio 4.1之后的版本进行开发时,创建的项目默认的主题都是Theme.MaterialComponents.DayNight.DarkActionBar。所有Button都是Material类型的Button,默认使用主题色。

解决方法:

? ? ? ? 在左侧project栏中找到app/src/main/res/values/themes.xml

?

将其中的

<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">

?修改为:

<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">

?或Theme.AppCompat下的任意一种主题:

<style name="Theme.MyApplication" parent="Theme.AppCompat.Light"> 解决后运行结果:

? ? ? ? ?这时候我们会发现问题已经被完美的解决啦~

-------------------------------------------------------------------------------------------分割线-----------------------------------------------------------------------------

? ? ? ? 在帖子发出去后经过博主和好友的交流学到了一种更为简单的方法,在使用Button时用android.widget.Button代替Button就可以不用那么麻烦的改设置啦,这无疑是一种更好的方法:

<Button android:id="@+id/btn_1"

改为:

<android.widget.Button android:id="@+id/btn_1"

即可(QAQ)


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #Android #button #背景