LoginSignup
0
0

More than 3 years have passed since last update.

CardViewの子要素をハミ出そうとした話

Last updated at Posted at 2019-09-15

やろうとしたこと

androidx.cardview.widget.CardViewのCardViewの中身のviewをネガティブマージンを使って外の領域まではみ出そうとした。

結論

CardViewを使うのをやめて、FrameLayoutで対応した。

検証

まずCardViewで試す

まずCardViewの子Viewに対してネガティブマージンを設定することによって、cardviewから領域をはみ出そうとした。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:padding="40dp"
    tools:context=".MainActivity">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginLeft="-8dp"
            android:layout_marginRight="-8dp"
            android:background="@color/colorAccent"
            android:text="Hello World!" />

    </androidx.cardview.widget.CardView>

</RelativeLayout>

レイアウトのプレビューは以下のようになっていました。おっハミ出てる!いい感じ!

スクリーンショット 2019-09-15 16.21.40.png

しかしビルド後

なぜだ、、はみ出ているべき領域がクロップされている。。

FrameLayoutで試す

原因究明のため試しにFrameLayoutでやってみる。レイアウトは以下。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:padding="40dp"
    tools:context=".MainActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF424242">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginLeft="-8dp"
            android:layout_marginRight="-8dp"
            android:background="@color/colorAccent"
            android:text="Hello World!" />

    </FrameLayout>

</RelativeLayout>

プレビューはこんな感じ。うん、さっきと同様ちゃんとハミ出てる。

スクリーンショット 2019-09-15 16.28.37.png

ビルド後

ちゃんとはみ出た!やはりCardViewの何らかの処理が原因っぽいが、コードを見てもそれらしき処理は見つけられず。。
なんとなくelevationとかが影響してそうかと思いましたが、cardElevation属性を0にして試しても同様にはみ出すことはできませんでした。

まとめ

今回はCardViewでなくても実現できるUIだったので、CardViewの採用をやめ、FrameLayoutで対応しました。
CardViewの子Viewを飛び出したい場合(あまりないと思いますが)は要注意です。

一応リポジトリはこちらです。
https://github.com/youmitsu/ClipChildrenSampleApp

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0