Wednesday, January 14, 2015

How to convert Hex color to int color in Android

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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="200dp"
        android:layout_height="75dp"
        android:text="Change My Color"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java

package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        Button button = findViewById(R.id.button);

        // Button click listener
        button.setOnClickListener(view -> {
            // #808000 equal to Olive color
            int deepColor = Color.parseColor("#808000");

            // #FFF5EE equal to SeaShell color
            int lightColor = Color.parseColor("#FFF5EE");

            // set the button background color
            // setBackgroundColor() method require to pass an int color
            button.setBackgroundColor(deepColor);

            // set the button text color
            // setTextColor() method require to pass an int color
            button.setTextColor(lightColor);
        });
    }
}