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

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

    <Button
    android:id="@+id/someName"
    android:layout_width="170dp"
    android:layout_height="70dp"
    android:layout_marginTop="10dp"
    android:text="@string/some_text" />

    ... other buttons...

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

【问题讨论】:

    标签: android xml android-layout button inheritance


    【解决方案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:width="100dp"
            android:height="20dp" />
    </selector>
    

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

    【讨论】:

    • 据我所知 res 文件夹中的所有名称都应该只包含小字符,然后 my_custom_button.xml 是允许的。无论如何,这不起作用。编译器抱怨应该扩展的属性不可见。
    • 这个方案比使用styles.xml更好吗?
    猜你喜欢
    • 2020-10-07
    • 2019-10-27
    • 2017-03-12
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2017-08-06
    • 1970-01-01
    相关资源
    最近更新 更多