Reputation: 39
I am trying to switch the color of my background with the click of a button. It shows the initial color(blue) and when I click it turns to the next color(red). When I click again it goes back to blue and quickly transitions to red not my third color (white). I have defined the colors in the colors.xml file and made a drawable resource called transition.xml file to transition.
transition.xml :
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/blue_background"></item>
<item android:drawable="@color/red_background"></item>
<item android:drawable="@color/white"></item>
"
</transition>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup layout = (ViewGroup) findViewById(R.id.main_layout);
TransitionDrawable transition = (TransitionDrawable) layout.getBackground();
Button button = (Button) findViewById(R.id.StartTransitionButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
transition.startTransition(500);
transition.startTransition(500);
transition.startTransition(500);
}
}
);
}
}
<?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="@drawable/transition"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/transition"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp"></LinearLayout>
Upvotes: 1
Views: 95
Reputation: 20346
TransitionDrawable supports only two layers
A TransitionDrawable is a drawable object that can cross-fade between the two drawable resources.
Upvotes: 1