我可以在我的应用程序中使用一个按钮和多个样式吗?

问题描述 投票:0回答:2

我对android样式技术相对较新,我试图围绕可重用​​组件。我的应用程序在其视图层次结构中分散了许多按钮,它们几乎完全相同(可变字体颜色和按钮颜色)。是否可以定义一个可绘制的按钮,然后可以应用不同的样式,这样,按钮有一个可绘制的定义作为背景应用于Button xml属性,如<Button> android:background="@drawable/basic_btn"</Button>然后自定义让我们通过样式说明按钮颜色, 就像是

<Button
style="@style/Button.Green"
android:background="@drawable/basic_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

那么如果我想要一个使用相同drawable的蓝色按钮,我可以设置如下:

<Button
style="@style/Button.Blue"
android:background="@drawable/basic_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

这可能吗?我在尝试这个时目前没有得到我想要的结果。

用答案编辑:

回顾我的帖子,我不相信我已经很好地描述了我的初始问题,我感谢所有回应过的人。我最初的问题是试图将不同的<styles>应用于drawable以实现不同的背景颜色,实际上并没有改变背景颜色。我的解决方案是这样的。

定义可绘制的形状:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:radius="3dp" />

接下来,将drawable指定为背景

<Button style="@style/Button.basic
android:background="@drawable/btn_basic"
/>

现在为了诀窍的核心:

<Button style="@style/Button.basic
android:background="@drawable/btn_basic"
android:backgroundTint="@color/seafoam"
/>

backgroundTint默认情况下似乎在drawable顶部添加颜色色调。这允许我定义一个形状,但在xml文件中使用时应用任何颜色。 backgroundTint

android android-styles
2个回答
0
投票

像这样使用TextView: -

<TextView
                android:id="@+id/reviewsTitleTxt"
                style="@style/txt_style_16sp_white_color_ffffff"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAllCaps="true"
                android:gravity="center"
                android:text="@string/reviews_txt"
                android:layout_gravity="center_vertical"/>

Where Style file is:-
Define style in style file

 <style name="txt_style_16sp_white_color_ffffff">
        <item name="android:textSize">@dimen/txt_size_16sp</item>
        <item name="android:textColor">@color/white_color_ffffff</item>
    </style>

0
投票

由于我们正在评论,你无法通过发布的答案解决这个问题,我会尽力帮助你。

  • 首先,您应该在@style/ .xml上定义所有常用属性
  • 其次,将@drawable/定义为每个按钮的背景:

背景可绘制:

<?xml version="1.0" encoding="utf-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android" 
        android:shape="rectangle">
  <corners android:radius="@dimen/button_round_radius"/>
  <solid android:color="@color/background_color"/>
</shape>

关于这一点的坏处是你必须创建一个具有相同属性的新drawable才能改变颜色。

同时查看已创建的主题/样式,可能有助于您参考此答案。

现在在你的按钮的XML声明上:

<Button
style="@style/YourCommonAttributesStyling"
android:background="@drawable/a_drawable_shape_like_the_above"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

参考:Android Material Design Button Styles

© www.soinside.com 2019 - 2024. All rights reserved.