In this tutorial, we will use a 3rd party library called AmbilWarna to implement a color picker into our app. We will then use the picked color and set the background of our Activity to it.
In build.gradle file add these dependency:-
implementation 'com.github.yukuku:ambilwarna:2.0.1'
In MainActivity.java class file add these lines of codes:-
package com.deftskill.colorpickerexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import yuku.ambilwarna.AmbilWarnaDialog;
public class MainActivity extends AppCompatActivity {
ConstraintLayout mLayout;
int mDefaultColor;
Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (ConstraintLayout) findViewById(R.id.layout);
mDefaultColor = ContextCompat.getColor(MainActivity.this, R.color.colorPrimary);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openColorPicker();
}
});
}
public void openColorPicker() {
AmbilWarnaDialog colorPicker = new AmbilWarnaDialog(this, mDefaultColor, new AmbilWarnaDialog.OnAmbilWarnaListener() {
@Override
public void onCancel(AmbilWarnaDialog dialog) {
}
@Override
public void onOk(AmbilWarnaDialog dialog, int color) {
mDefaultColor = color;
mLayout.setBackgroundColor(mDefaultColor);
}
});
colorPicker.show();
}
}
In activity_main.xml file add these lines of codes:-
<?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:id="@+id/layout"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open color picker"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>After adding these lines of codes run this application.

Comments