必需的自定义属

Mik*_*ler 9 android

android:layout_width和android:layout_height是必需的属性,即如果你没有为Layout指定它们,Android Studio会告诉我"Element x没有必需的属性android:layout_height".

我在我自己的类中定义了一些自定义属性,我想要求在xml中使用它们的任何人都指定值,就像他们必须指定layout_width和layout_height一样.

我怎么做?我可以在attrs.xml中添加一些内容:

<declare-styleable name="MyStyleable">
   <attr name="myAttribute" format="float"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

或者也许在style.xml中:

<style name="MyStyle">
    <item name="myAttribute">3</item>
</style>
Run Code Online (Sandbox Code Playgroud)

Iva*_*sov 14

AFAIK,目前attr没有任何属性来强制标记它们.("layout_width"以及类似的是非常常见的错误,检查那些是连接到SDK)

但是,如果缺少某个属性(您可以通过调用确定),则可以RuntimeException从自定义中抛出一个- 在方法中执行此操作.ViewTypedArray.hasValue()TypedArraygetLayoutDimension()

这正是您"layout_width"使用命令行工具编译缺少某个地方的应用程序时所获得的行为(即没有Eclipse或Idea来检测缺少的属性并阻止您编译):您运行应用程序并立即崩溃并RuntimeException说出您'缺少属性.