0
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.example.league95.ourownbutton.MainActivity">

<TextView
    android:id="@+id/gg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"/>

<Button
    android:id="@+id/btn"
    android:layout_width="292dp"
    android:layout_height="wrap_content"
    android:onClick="clickMe"
    android:text="Click"
    tools:layout_editor_absoluteX="46dp"
    tools:layout_editor_absoluteY="231dp"/>

</android.support.constraint.ConstraintLayout>

This code produces this on the emulator:

enter image description here

However, when I run my code on my physical phone, instead of getting the above image, I get something like the following: enter image description here

No matter how many ways I center the Button, when I run it on my phone it goes to the top left corner. This only happens with ConstraintLayout for some reason. What gives?

Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
John Doe
  • 211
  • 2
  • 13

2 Answers2

2

To center your button within a ConstraintLayout, you must define layout constraints for your Button widget.

<Button
    android:id="@+id/btn"
    android:layout_width="292dp"
    android:layout_height="wrap_content"
    android:text="Click"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent" />
AlexTa
  • 5,133
  • 3
  • 29
  • 46
2

enter image description here

<TextView
    android:id="@+id/gg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="Hello World!"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btn"
    android:layout_width="292dp"
    android:layout_height="wrap_content"
    android:onClick="clickMe"
    android:text="Click"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/gg" />

</android.support.constraint.ConstraintLayout>
Shweta Chauhan
  • 6,739
  • 6
  • 37
  • 57