【问题标题】:Drawable padding overrides layout padding可绘制填充覆盖布局填充
【发布时间】:2014-07-23 03:35:27
【问题描述】:

我有一个这样的 TextView:

<TextView
   android:id="@+id/friends"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:padding="8dp" />

我设置的背景是这样的:

textView.setBackgroundResource(R.drawable.background_color);

background_color.xml 在哪里:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="#217dd2" />
    </shape>
</item>
<item
    android:left="5dip">
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
        <solid android:color="#deebf6" />
    </shape>
</item>

这将删除我的默认填充 8dp 并将其替换为我在分层列表的第二项中声明的 5dp 的左侧填充。有什么办法可以避免这种情况?或者另一种为视图创建 2 色背景的方法?

【问题讨论】:

    标签: android android-drawable


    【解决方案1】:

    这是已知问题,setBackgroundResource 方法会重置填充。 尝试从 XML 设置背景:

    <TextView
       android:id="@+id/friends"
       android:background="@drawable/background_color"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:padding="8dp" />
    

    在这种情况下它会正常工作。

    【讨论】:

    • 好的,但是如果您单击视图,我将使用此背景作为选定状态。默认值为纯白色。所以我不想直接在xml中设置。
    • 如果你需要不同的背景来选择和默认状态,你应该在xml中将它定义为selectordrawable。
    • 其实我才发现我用textView.setPadding(8, 8, 8, 8);设置背景资源后可以设置padding
    • 是的,它可以是一个选项。但请注意,setPadding 需要以像素为单位的填充,因此如果您希望它与密度无关,则需要对其进行转换。
    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多