Blog purpose for android basic example for android app developer. any query please my contact

Wednesday, 20 May 2020

how to change listview background color in android studio

how to change listview background color in android studio

In this, An article today learns how to change the background color in a listview item on an android studio. Follow the method change listview color in android studio.

 

In Android development, any time we need to present a vertical list of scrollable items we can have the ListView which gets information populated using the device. The simplest device to take is called the ArrayAdapter because this device converts the ArrayList of objects into perspective items loaded into the ListView container.

 

In Android development, any time we need to present a vertical list of scrollable items we can have the ListView which gets information populated using the device. The simplest device to take is called the ArrayAdapter because this device converts the ArrayList of objects into perspective items loaded into the ListView container.

 

Follow the full source code  how to change the background-color in listview item on android:


1.build.gradle:

 implementation 'com.android.support:recyclerview-v7:23.1.1'
    implementation 'com.jakewharton:butterknife:7.0.1'


2.MainActivity.java:

package com.akash.colorlist;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.rvColors)
    RecyclerView rvColors;
    @Bind(R.id.rgOperations)
    RadioGroup rgOperations;
    @Bind(R.id.cbPredictive)
    CheckBox cbPredictive;
    @Bind(R.id.cbCustomAnimator)
    CheckBox cbCustomAnimator;

    private ColorsAdapter colorsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setupColorsList();
    }

    private void setupColorsList() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return cbPredictive.isChecked();
            }
        };
        rvColors.setLayoutManager(layoutManager);

        colorsAdapter = new ColorsAdapter(this);
        rvColors.setAdapter(colorsAdapter);

        setupRecyclerViewAnimator();
    }

    public void onColorsListItemClicked(View view) {
        int itemAdapterPosition = rvColors.getChildAdapterPosition(view);
        if (itemAdapterPosition == RecyclerView.NO_POSITION) {
            return;
        }

        int checkedRadioButton = rgOperations.getCheckedRadioButtonId();
        if (checkedRadioButton == R.id.rbDelete) {
            colorsAdapter.removeItemAtPosition(itemAdapterPosition);
        } else if (checkedRadioButton == R.id.rbAdd) {
            colorsAdapter.addItemAtPosition(itemAdapterPosition + 1);
        } else if (checkedRadioButton == R.id.rbChange) {
            colorsAdapter.changeItemAtPosition(itemAdapterPosition);
        }
    }

    @OnCheckedChanged(R.id.cbCustomAnimator)
    public void onCustomAnimatorCheckedChange() {
        setupRecyclerViewAnimator();
    }

    private void setupRecyclerViewAnimator() {
        if (cbCustomAnimator.isChecked()) {
            rvColors.setItemAnimator(new MyItemAnimator());
        } else {
            rvColors.setItemAnimator(new DefaultItemAnimator());
        }
    }
}


3.create class MyItemAnimator.java:

package com.akash.colorlist;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Miroslaw Stanek on 06.01.2016.
 */
public class MyItemAnimator extends DefaultItemAnimator {

    HashMap<RecyclerView.ViewHolder, AnimatorInfo> animatorMap = new HashMap<>();

    @Override
    public boolean canReuseUpdatedViewHolder(RecyclerView.ViewHolder viewHolder) {
        return true;
    }

    @NonNull
    @Override
    public RecyclerView.ItemAnimator.ItemHolderInfo recordPreLayoutInformation(@NonNull RecyclerView.State state,
                                                                               @NonNull RecyclerView.ViewHolder viewHolder,
                                                                               int changeFlags,
                                                                               @NonNull List<Object> payloads) {
        ColorTextInfo colorTextInfo = new ColorTextInfo();
        colorTextInfo.setFrom(viewHolder);
        return colorTextInfo;
    }

    @NonNull
    @Override
    public ItemHolderInfo recordPostLayoutInformation(@NonNull RecyclerView.State state,
                                                      @NonNull RecyclerView.ViewHolder viewHolder) {
        ColorTextInfo colorTextInfo = new ColorTextInfo();
        colorTextInfo.setFrom(viewHolder);
        return colorTextInfo;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean animateChange(@NonNull RecyclerView.ViewHolder oldHolder,
                                 @NonNull final RecyclerView.ViewHolder newHolder,
                                 @NonNull ItemHolderInfo preInfo,
                                 @NonNull ItemHolderInfo postInfo) {
        final ColorsAdapter.ColorViewHolder holder = (ColorsAdapter.ColorViewHolder) newHolder;
        final ColorTextInfo preColorTextInfo = (ColorTextInfo) preInfo;
        final ColorTextInfo postColorTextInfo = (ColorTextInfo) postInfo;

        ObjectAnimator fadeToBlack = ObjectAnimator.ofArgb(holder.itemView, "backgroundColor", preColorTextInfo.color, Color.BLACK);
        ObjectAnimator fadeFromBlack = ObjectAnimator.ofArgb(holder.itemView, "backgroundColor", Color.BLACK, postColorTextInfo.color);
        AnimatorSet bgAnim = new AnimatorSet();
        bgAnim.playSequentially(fadeToBlack, fadeFromBlack);

        ObjectAnimator oldTextRotate = ObjectAnimator.ofFloat(holder.tvColor, View.ROTATION_X, 0, 90);
        ObjectAnimator newTextRotate = ObjectAnimator.ofFloat(holder.tvColor, View.ROTATION_X, -90, 0);
        oldTextRotate.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                holder.tvColor.setText(preColorTextInfo.text);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                holder.tvColor.setText(postColorTextInfo.text);
            }
        });
        AnimatorSet textAnim = new AnimatorSet();
        textAnim.playSequentially(oldTextRotate, newTextRotate);

        AnimatorSet overallAnim = new AnimatorSet();
        overallAnim.playTogether(bgAnim, textAnim);
        overallAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                dispatchAnimationFinished(newHolder);
                animatorMap.remove(newHolder);
            }
        });

        AnimatorInfo animatorInfo = animatorMap.get(newHolder);
        if (animatorInfo != null) {
            boolean firstHalf = animatorInfo.oldTextRotator.isRunning();
            if (firstHalf) {
                fadeToBlack.setCurrentPlayTime(animatorInfo.fadeToBlackAnim.getCurrentPlayTime());
                oldTextRotate.setCurrentPlayTime(animatorInfo.oldTextRotator.getCurrentPlayTime());
            } else {
                fadeToBlack.setCurrentPlayTime(animatorInfo.fadeToBlackAnim.getDuration());
                oldTextRotate.setCurrentPlayTime(animatorInfo.oldTextRotator.getDuration());
                newTextRotate.setCurrentPlayTime(animatorInfo.newTextRotator.getCurrentPlayTime());
                fadeFromBlack.setIntValues((Integer)animatorInfo.fadeFromBlackAnim.getAnimatedValue(), postColorTextInfo.color);
            }

            animatorInfo.overallAnim.cancel();
            animatorMap.remove(newHolder);
        }

        animatorMap.put(newHolder, new AnimatorInfo(
                overallAnim, fadeToBlack, fadeFromBlack, oldTextRotate, newTextRotate
        ));

        overallAnim.start();

        return super.animateChange(oldHolder, newHolder, preInfo, postInfo);
    }

    private class ColorTextInfo extends ItemHolderInfo {
        int color;
        String text;

        @Override
        public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder) {
            if (holder instanceof ColorsAdapter.ColorViewHolder) {
                ColorsAdapter.ColorViewHolder colorViewHolder = (ColorsAdapter.ColorViewHolder) holder;
                color = ((ColorDrawable) colorViewHolder.itemView.getBackground()).getColor();
                text = (String) colorViewHolder.tvColor.getText();
            }
            return super.setFrom(holder);
        }
    }

    private class AnimatorInfo {
        Animator overallAnim;
        ObjectAnimator fadeToBlackAnim, fadeFromBlackAnim, oldTextRotator, newTextRotator;

        public AnimatorInfo(Animator overallAnim, ObjectAnimator fadeToBlackAnim, ObjectAnimator fadeFromBlackAnim,
                            ObjectAnimator oldTextRotator, ObjectAnimator newTextRotator) {
            this.overallAnim = overallAnim;
            this.fadeToBlackAnim = fadeToBlackAnim;
            this.fadeFromBlackAnim = fadeFromBlackAnim;
            this.oldTextRotator = oldTextRotator;
            this.newTextRotator = newTextRotator;
        }
    }


}


4.create a class ColorsAdapter.java:

package com.akash.colorlist;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Miroslaw Stanek on 06.01.2016.
 */
public class ColorsAdapter extends RecyclerView.Adapter<ColorsAdapter.ColorViewHolder> {

    private MainActivity mainActivity;
    private ArrayList<Integer> colors = new ArrayList<>();

    public ColorsAdapter(MainActivity mainActivity) {
        this.mainActivity = mainActivity;
        colors.addAll(ColorsHelper.COLORS);
    }

    @Override
    public ColorViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ColorViewHolder colorViewHolder = new ColorViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainActivity.onColorsListItemClicked(v);
            }
        });
        return colorViewHolder;
    }

    @Override
    public void onBindViewHolder(ColorViewHolder holder, int position) {
        int color = colors.get(position);
        holder.itemView.setBackgroundColor(color);
        holder.tvColor.setText("#" + Integer.toHexString(color));
    }

    @Override
    public int getItemCount() {
        return colors.size();
    }

    public void removeItemAtPosition(int position) {
        colors.remove(position);
        notifyItemRemoved(position);
    }

    public void addItemAtPosition(int position) {
        colors.add(position, ColorsHelper.COLORS.get(position));
        notifyItemInserted(position);
    }

    public void changeItemAtPosition(int position) {
        colors.set(position, ColorsHelper.getRandomColor());
        notifyItemChanged(position);
    }

    static class ColorViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.tvColor)
        TextView tvColor;

        public ColorViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


5.create class ColorsHelper.java:

package com.akash.colorlist;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * Created by Miroslaw Stanek on 06.01.2016.
 */
public class ColorsHelper {
    //Some randomly picked colors from SDK's color.xml
    public static final List<Integer> COLORS = Arrays.asList(
            0xff00bcd4, 0xff3f51b5, 0xff4285f4, 0xffe91e63, 0xff0f9d58, 0xff8bc34a, 0xffff9800,
            0xffff5722, 0xff9e9e9e, 0xff00796b, 0xff00695c, 0xff3367d6, 0xff2a56c6, 0xff303f9f,
            0xff283593, 0xff7b1fa2, 0xff6a1b9a, 0xffc2185b, 0xff00bcd4, 0xff3f51b5, 0xff4285f4,
            0xffe91e63, 0xff0f9d58, 0xff8bc34a, 0xffff9800, 0xffff5722, 0xff9e9e9e, 0xff00796b,
            0xff00695c, 0xff3367d6, 0xff2a56c6, 0xff303f9f, 0xff283593, 0xff7b1fa2, 0xff6a1b9a,
            0xffc2185b, 0xff00bcd4, 0xff3f51b5, 0xff4285f4, 0xffe91e63, 0xff0f9d58, 0xff8bc34a,
            0xffff9800, 0xffff5722, 0xff9e9e9e, 0xff00796b, 0xff00695c, 0xff3367d6, 0xff2a56c6,
            0xff303f9f, 0xff283593, 0xff7b1fa2, 0xff6a1b9a, 0xffc2185b
    );

    public static Integer getRandomColor() {
        return COLORS.get(new Random().nextInt(COLORS.size()));
    }
}


6.create a xml file list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="96dp">

    <TextView
        android:id="@+id/tvColor"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#ffffff"
        android:textSize="32sp" />
</FrameLayout>


7.activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="frogermcs.io.recyclerviewanimations.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvColors"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        tools:listitem="@layout/list_item" />

    <RadioGroup
        android:id="@+id/rgOperations"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rbDelete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="Delete" />

        <RadioButton
            android:id="@+id/rbAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add" />

        <RadioButton
            android:id="@+id/rbChange"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change" />
    </RadioGroup>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp">

        <CheckBox
            android:id="@+id/cbPredictive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Predictive Animations" />

        <CheckBox
            android:id="@+id/cbCustomAnimator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Custom Animator" />
    </LinearLayout>

</LinearLayout>



No comments:

Post a Comment