【问题标题】:Android styles doesn't allow colorsAndroid 样式不允许使用颜色
【发布时间】:2017-03-09 23:26:56
【问题描述】:

我是安卓开发新手。 我正在做一个程序,我想改变按钮样式,我可以做到。

这里是关于按钮样式推荐的图片:

如您所见,它既光滑又漂亮!但是当我想改变按钮的颜色(带有样式)时,我遇到了问题! :

如何更改样式(按钮颜色)并保持按钮平滑美观?

【问题讨论】:

标签: android


【解决方案1】:

更改背景颜色会删除默认的材料设计样式,您应该为该按钮创建自己的样式,父主题为Widget.AppCompat.Button.Colored

 <!--fix to keep material design for buttons and add background color-->
    <style name="blackButton" parent="Widget.AppCompat.Button.Colored">
        <item name="colorButtonNormal">@color/colorBlack</item>
    </style>

然后使用android:theme="@style/blackButton"将此主题应用于按钮

【讨论】:

  • 在你回答我的问题之前,我更改了accentColor(在他们的编辑器中),但是当我看到你的回答时,我确实添加了你的文本,但它没有用!
【解决方案2】:

制作一种扩展默认按钮样式并为其设置背景颜色的样式。 在styles.xml中

<style name="black_button_style"
       parent="Base.Widget.AppCompat.Button.Colored">
             <item name="android:layout_width">match_parent</item>
             <item name="android:layout_height">wrap_content</item>
             <item name="android:typeface">sans</item>
             <item name="android:background">#000000</item>
</style>

在您的活动 xml 中。

   <Button 
    style="@style/black_button_style/>

【讨论】:

  • 我这样做了,但它给了我相同的结果(相同的结果意味着我的问题中的第二张图片)
  • 你能给我一个代码sn-p吗?根据图片你不需要同时给出样式和颜色。
【解决方案3】:

在styles.xml中添加这段代码

<resources>
 <style name="App.Button.Style" parent="Base.Widget.AppCompat.Button.Colored">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@color/red</item>
        <item name="android:textColor">@android:color/white</item>
    </style>
</resources>

并更改您的按钮样式

 <Button
     android:id="@+id/btnPlayVideo"
     android:text="Play Video"
     style="@style/App.Button.Style"/>

【讨论】:

    【解决方案4】:

    使用风格作为主题:

     <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            android:textColor="@android:color/white"
            android:theme="@style/blackButton"
        />
    

    并在你的styles.xml中添加这个样式

    <style name="blackButton" parent="Widget.AppCompat.Button.Colored">
            <item name="colorButtonNormal">@android:color/black</item>
            <item name="colorControlHighlight">@color/colorAccent</item>
        </style>
    

    【讨论】:

    • 谢谢!但我还有一个问题,我可以添加像数组这样的样式吗?我的意思是我有 10 种材质颜色,我想用这些颜色添加 10 种样式,我可以添加类似数组的样式吗?
    • 数组如??我没明白你的问题。你想在一个中添加不同的样式吗?
    • 不,我的意思是,当我们要添加这么多项目时,我们使用 Array ,例如:double[] myList = {1.9, 2.9, 3.4, 3.5};现在我想设置多种颜色作为样式,我可以使用数组吗?
    • 我认为没有任何方法可以实现这一点。据我所知,您必须在 xml 中定义样式,然后将它们动态添加到视图中。但是,如果您只想在布局中更改具有相同主题的颜色,则可以将 android:backgroundTint="@color/desiredcolor" 用于具有所需颜色的按钮。 (注意:backgroundTint 属性仅在 API 21 或更高版本中使用)。
    猜你喜欢
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2015-10-21
    • 2015-06-20
    相关资源
    最近更新 更多