Thursday, October 1, 2020

android kotlin - Chip center text

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // set chip text alignment center programmatically
        chipYellow.textAlignment = View.TEXT_ALIGNMENT_CENTER
    }
}
activity_main.xml

<?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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FEFEFA"
    tools:context=".MainActivity">

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <!-- chip center text in xml -->
        <com.google.android.material.chip.Chip
            android:id="@+id/chipCrimson"
            android:layout_width="175dp"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:text="Crimson" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="175dp"
            android:layout_height="wrap_content"
            android:text="Yellow" />

    </com.google.android.material.chip.ChipGroup>

</androidx.constraintlayout.widget.ConstraintLayout>