Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding margin to TextView in Constraint Layout using XML

I want to add left and right margins to TextView Widget but it doesn't seem to be working.

Here's my activity XML:

<?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.sayhi.DisplayOutput"
    tools:layout_editor_absoluteY="81dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="140dp"
        android:text="@string/output"
        android:textSize="30sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Here's what it looks like:

enter image description here

I am using GUI layout editor. I tried adding padding to the widget and padding works as expected. I think I am missing something basic about layout but I am not sure what.

I am using Android Studio 2.3, ConstraintLayout 1.0.2, AppCompat v7:26, Build Tools Version 26.0.2.

like image 410
vadasambar Avatar asked Oct 27 '17 16:10

vadasambar


People also ask

Which is better RelativeLayout or ConstraintLayout?

If you have the choice start with ConstraintLayout, but if you already have your app in RelativeLayout, stay with it. That's all I have been following. RelativeLayout is very limited in functionality and many complex layouts can't be made using it, especially when ratios are involved.

What is 0dp in constraint layout?

Widgets dimension constraints Using 0dp , which is the equivalent of " MATCH_CONSTRAINT "

Can we use LinearLayout in ConstraintLayout?

Most of what can be achieved in LinearLayout and RelativeLayout can be done in ConstraintLayout. However, learning the basics of LinearLayout and RelativeLayout is important before trying to understand how to use it with ConstraintLayout.

How do I center a TextView layout?

When you have a LinearLayout view, you can center the TextView widget by setting the layout_width and layout_height attributes of the TextView to match_parent and the gravity attribute to center . You can also center multiple TextView widgets by using the layout_weight attribute.


1 Answers

Change

android:layout_width="wrap_content"

to

android:layout_width="match_parent"
// or 
android:layout_width="0dp"

As TextView 's width .

like image 59
KeLiuyue Avatar answered Nov 07 '22 22:11

KeLiuyue