android - 声明样式和样式之间的区别

标签 android styles declare-styleable

我已经开始在我的 android 应用程序中使用样式等,并且到目前为止我已经完成了所有工作。我很理解“风格”section of the guide .

但是,环顾四周,如 this thread ,我无法真正弄清楚两者之间的区别(declare-stylablestyle)。 根据我的理解 declare-styleable 获取其中指定的属性并将其指定为可样式化,然后根据需要从代码中对其进行更改。

但如果真的是这样,在布局中定义属性不是更简单吗?或者声明一个指定它的样式?

最佳答案

我认为将属性声明为可样式化与否只有以下区别。

在 attrs.xml 中,您可以直接在“resources”部分或“declare-styleable”中声明自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <attr name="attrib1" format="string" />
 <declare-styleable name="blahblah">
    <attr name="attrib2" format="string" />
 </declare-styleable>

所以现在我们将“attrib1”定义为不可样式化,将“attrib2”定义为可样式化。

layout/someactivity.xml 我们可以直接使用这些属性(不需要命名空间):

<com.custom.ViewClass  attrib1="xyz" attrib2="abc"/>

您可以在 style.xml 声明中使用“styleable”属性“attrib2”。同样,这里不需要命名空间(即使在布局 XML 中使用了命名空间)。

 <style name="customstyle" parent="@android:style/Widget.TextView">
    <item name="attrib2">text value</item>
    <!--  customize other, standard attributes too: -->
    <item name="android:textColor">@color/white</item>
 </style>

然后你也可以设置每个样式的属性。

<com.custom.CustomView attrib1="xyz" style="@style/customstyle"/>

假设我们这样做:我们直接在 XML 中设置 attrib1,我们在样式中设置 attrib2

我在其他地方看到描述说“blahblah”必须是使用这些属性的自定义 View 类的名称,并且您需要使用命名空间来引用您的自定义属性布局 XML。但这些似乎都没有必要。

styleable 和 non-styleable 的区别似乎在于:

  • 您可以在“style.xml”声明中使用可样式化的属性。
  • 自定义类的构造函数需要以不同的方式读取样式属性和非样式属性:样式属性用obtainStyledAttributes(),非样式属性用 attr.getAttributeValue() 或类似的。

在我在网上看到的大多数教程和示例中,只使用了 obtainStyledAttributes()。但是,这不适用于直接在布局中声明的属性,而不使用样式。如果你像大多数教程中所示的那样执行obtainStyledAttributes(),你根本不会得到属性attrib1;你只会得到 attrib2 因为它是在样式中声明的。使用 attr.getAttributeValue() 的直接方法有效:

 public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    String attrib1 = attrs.getAttributeValue(null, "attrib1");
    // do something with this value
 }

由于我们没有使用命名空间来声明“attrib1”,因此我们将 null 作为命名空间参数传递给 getAttributeValue()

关于android - 声明样式和样式之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4585808/

相关文章:

android - 修复Gradle错误 “Attribute ” xxx“已经在Android Studio中定义”的有效方法?

java - 类转换异常 : Integer cannot be cast to Long

android - 如何在 Android Oreo (8.1) 或更高版本中从 URI 获取文件路径

java - Java 和 Android 中对象的作用域和销毁

javascript - 在菜单项鼠标悬停时更改标题底部边框颜色

android - 使用可样式属性时出现 NumberFormatException

Android:Theme.Holo 不是黑色

angular - 仅在 Angular Material 工具提示中的第一行应用样式

Android: <declare-styleable> 方法属性

java - 如何通过反射从 declare styleable TypedArray 获取值?