This view is not constrained ~ エラーの対策

This view is not constrained horizontally: at runtime it will jump to the left
unless you add a horizontal constraint less… のエラーが発生した時のソースコードと対策を備忘録で残しておきます。

エラー:
This view is not constrained horizontally: 
at runtime it will jump to the left unless you add a horizontal constraint less…

エラー発生時のコードは以下。
Android Studioが自動生成してくれるLayoutにviewを追加しただけ。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <View
        android:id="@+id/hogehoge"
        android:layout_width="100dp"
        android:layout_height="100dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

修正後は以下
結論から言うと、追加したviewに対してきちんとLayoutを定義すれば解決。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <View
            android:id="@+id/hogehoge"
            android:layout_width="100dp"
            android:layout_height="100dp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Layoutの知識はきちんと整理しておかないといけないですね。

mana99 について

30代のシステムエンジニア 仕事以外にAndroidアプリを定期的にリリース モットーは「最短&シンプル」
カテゴリー: エラー関連 タグ: , パーマリンク