Search code examples
javaandroidtransitionandroid-drawable

App crashes when using TransitionDrawable


I want to transition the color of my background when a button is clicked but my app seems to crash once I press the button. The button runs the TransitionDrawable code. I have set my background to the drawable folder containing the transition.Could anyone help me? Thank you very much!

public class MainActivity extends AppCompatActivity {

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


    }

    public void colourChangeButton(View view) {

       final TransitionDrawable transition = (TransitionDrawable) view.getBackground();
        transition.startTransition(1000);

  }
}

Here are my drawable files that define the colours:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <color android:color="#2575fc"></color>
    </item>

</selector>




<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <color android:color="#ff0844"></color>
    </item>

</selector>

Here is my transition drawable file :

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/blue_background"></item>
    <item android:drawable="@drawable/pink_background"></item>
    </transition>

Solution

  • You are almost there!

    You need to set the transition drawable as the background of your view.

    Let's say your activity's layout xml is called activity_main.xml and your transition drawable file is called transition.xml.

    In the root layout of your activity_main.xml:

    <LinearLayout
       ... 
       id="@+id/main_layout"
       background="@drawable/transition">
    
        <Button
            id="@+id/start_transition_button"
            ... />
        ...
    

    In MainActivity.java:

    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.start_transition_button);
    
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    transition.startTransition(500);
                }
            }
        }
    }
    

    Here is a good post about it: https://proandroiddev.com/transitiondrawable-small-gems-of-the-android-framework-4dcdd3c83319