Android:xml中组件的继承

Posted

技术标签:

【中文标题】Android:xml中组件的继承【英文标题】:Android: inheritance of components in xml 【发布时间】:2013-12-26 11:44:36 【问题描述】:

我的 Activity 上有 5 个按钮,它们之间的区别仅在于值 height

    <Button
    android:id="@+id/someName"
    android:layout_
    android:layout_
    android:layout_marginTop="10dp"
    android:text="@string/some_text" />

    ... other buttons...

是否可以从第一个按钮扩展 4 个按钮并仅更改其中一个属性? 我知道样式是可能的,但是组件呢? 或者也许我应该在 java 代码中执行此操作,但是如何连接到特定的类?

【问题讨论】:

【参考方案1】:

我找到了详细的答案:http://docs.xamarin.com/recipes/android/resources/general/style_a_button/

我自己的例子基于上面的 URL:

1) res\drawable\category_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape android:shape="rectangle">
            <solid android:color="#ef4444" />

            <corners android:radius="15dp" />
        </shape></item>
    <item><shape android:shape="rectangle">
            <solid android:color="#D8D8D8" />

            <corners android:radius="15dp" />
        </shape></item>

</selector>

2) res\layout\some_activity.xml

 ... some xml code ...
 <Button
        android:id="@+id/buttonTestCatA"
        style="@style/category_button"
        android:background="@drawable/category_button"
        android:text="@string/test_cat_A" />
... some xml code ...

3) res\values\styles.xml

<resources>

    <style name="AppBaseTheme" parent="Theme.AppCompat.Light"></style>

    <style name="AppTheme" parent="AppBaseTheme"></style>

    <style name="category_button">
        <item name="android:layout_width">170dp</item>
        <item name="android:layout_height">70dp</item>
        <item name="android:layout_margin">5dp</item>
        <item name="android:textSize">25sp</item>
    </style>

</resources>

【讨论】:

请从链接中提取关键注释并将它们添加到您的答案中,以便即使链接失效也可以理解。您也可以接受自己的答案。【参考方案2】:

您必须在您的drawable 文件夹中创建一个新的XML 文件。例如,我们将其重命名为myCustomButton.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:
        android: />
</selector>

然后,对于您希望获得相同行为的每个按钮,添加以下行:android:background="@drawable/myCustomButton".

【讨论】:

据我所知 res 文件夹中的所有名称都应该只包含小字符,然后 my_custom_button.xml 是允许的。无论如何,这不起作用。编译器抱怨应该扩展的属性不可见。 这个方案比使用styles.xml更好吗?

以上是关于Android:xml中组件的继承的主要内容,如果未能解决你的问题,请参考以下文章

Android四大组件之BroadcastReceiver

Android 核心组件之 Activity

[Android] 开发第八天

继承自两个父主题的 Android XML 主题?

自定义View(三)——继承ViewGroup实例

android 文本输入框里面如何添加别的组件???