TransitionDrawable का उपयोग करके View के बैकग्राउंड कलर को स्मूथली एनिमेट करने का तरीका।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में नया प्रोजेक्ट बनाएं।
चरण 2: लेआउट
res/layout/activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/textView"
android:layout_centerInParent="true"
android:layout_marginBottom="15dp"
android:text="Animate background color" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Changing Background color of this view."
android:textSize="36sp"
android:textStyle="bold" />
</RelativeLayout>
चरण 3: एनिमेशन लॉजिक
src/MainActivity.java:
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
button.setOnClickListener(v -> {
ColorDrawable[] colorDrawables = {
new ColorDrawable(Color.RED),
new ColorDrawable(Color.BLUE),
new ColorDrawable(Color.GREEN)
};
TransitionDrawable transitionDrawable = new TransitionDrawable(colorDrawables);
textView.setBackground(transitionDrawable);
transitionDrawable.startTransition(2000); // 2 सेकंड
});
}
}
चरण 4: मैनिफेस्ट
मानक मैनिफेस्ट।
व्याख्या
ColorDrawable- ठोस रंग ड्रॉएबलTransitionDrawable- ड्रॉएबल सरणी के बीच क्रॉस-फेड एनिमेशनstartTransition(ms)- मिलीसेकंड में अवधि- आधुनिक विकल्प:
ObjectAnimatorयाValueAnimatorके साथbackgroundColorप्रॉपर्टी
वैकल्पिक: ObjectAnimator दृष्टिकोण (API 21+)
ObjectAnimator animator = ObjectAnimator.ofObject(view, "backgroundColor",
new ArgbEvaluator(), Color.RED, Color.BLUE);
animator.setDuration(2000);
animator.start();