【问题标题】:Is it Possible to remove child padding In Android是否可以在Android中删除子填充
【发布时间】:2021-12-21 12:21:57
【问题描述】:

我有一个线性布局。在家长看来,我已经定义了填充。但我想从子视图中删除填充。是否可以删除中间子视图填充?我知道一种解决方案是我需要单独提供填充。但我不想使用这个解决方案。所以任何替代解决方案。

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tool="http://schemas.android.com/tools"
    android:padding="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:visibility="gone"
        tool:text="Header text" />

    <View
        android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginTop="10dp"
        android:background="#cccccc"
        android:visibility="gone"
        app:layout_constraintTop_toBottomOf="@id/header" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/dialog_recyclerview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp" />

</LinearLayout>

上面的代码是这样的

预期输出

【问题讨论】:

  • 如果您不希望它具有通用性,答案是不要在父级上放置填充。相反,在元素上放置边距。如果因为元素很多而这很困难,请使用第二个布局将它们分组并将其放在组中。

标签: android android-layout android-linearlayout android-constraintlayout


【解决方案1】:

这可以在 LinearLayout 中添加

android:clipToPadding="false"

并在视图中设置负水平边距:

android:layout_marginStart="-16dp"
android:layout_marginEnd="-16dp"

这是因为你有一个 LinearLayout,似乎除了 LinearLayout 和 RelativeLayout 之外的其他 ViewGroup 不支持负边距,因为这个答案说:https://stackoverflow.com/a/10673572/7794806

【讨论】:

  • 该链接已过期。 ConstraintLayout 从 210-alpha-2 开始支持负边距,请参阅 here
  • @JesúsBarrera 效果很好。你能解释一下android:clipToPadding 在做什么吗?
  • @vivekmodi 设置 clipToPadding=false 可避免 LinearLayout 的子级在超出填充限制时被修剪,这可能在滚动或动画期间发生。我已经看到这经常在回收站视图中使用。感谢您接受我的回答。
  • @JesúsBarrera 为什么它不能在程序中工作?
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 2013-07-18
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多