【问题标题】:Programmatically create ListView with custom style - Why is android:layout_marginXY not recognized?以编程方式创建具有自定义样式的 ListView - 为什么无法识别 android:layout_marginXY?
【发布时间】:2014-07-30 23:32:28
【问题描述】:

我正在尝试以编程方式创建一个新的 ListView 并将自定义样式应用于:

// Somewhere within a Fragment...
ListView myListView = new ListView(getActivity(), null, R.attr.myListViewStyle);
someContainerView.addView(myListView);

// In attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="AppTheme">
        <attr name="myListViewStyle" format="reference"/>
    </declare-styleable>
</resources>

// in styles.xml
<style name="AppTheme" parent="AppBaseTheme">
    <item name="myListViewStyle">@style/ListViewStyle</item>
</style>

<style name="BookingsSectionListView" parent="@android:style/Widget.ListView">
    <!-- Setting the Padding DOES work... -->
    <item name="android:paddingLeft">50dp</item>

    <!-- ...while setting the Margin has NO effect -->
    <item name="android:layout_marginTop">50dp</item>  
</style>

虽然创建 ListView 没有问题,但未正确应用自定义样式。 android:layout_marginXY 属性无法识别,因此未正确放置 ListView。如果我使用 android:paddingX 代替一切正常。 为什么会这样?

如果我不以编程方式而是直接在 XML 中创建 ListView 并将样式应用于它,android:layout_marginXY 属性可以正常工作。

创建 ListView 与在 XML 或 Java 中应用样式有什么区别?

【问题讨论】:

    标签: android android-layout android-listview android-styles


    【解决方案1】:

    您不应将layout_* 属性视为子样式的一部分(在本例中为ListView)。
    layout_* 属性位于添加子元素的父元素的上下文中。他们告诉父母在哪里定位以及如何布局孩子(孩子没有这个逻辑)。

    在这一行:

    ListView myListView = new ListView(getActivity(), null, R.attr.myListViewStyle);
    

    所有属性都传递给ListView,样式将应用于ListView 本身。它没有任何父对象 - 它只是新创建的对象,尚未附加到视图层次结构。

    someContainerView.addView(myListView);
    

    这是将LayputParams 分配给子级的行。您没有指定任何LayoutParams(此方法有不同的版本),因此将使用默认的。

    【讨论】:

    • 非常感谢!这让事情变得更加清晰!
    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 2011-02-26
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    相关资源
    最近更新 更多