[英]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.
该按钮运行TransitionDrawable代码。 I have set my background to the drawable folder containing the transition.Could anyone help me?
我已将我的背景设置为包含过渡的drawable文件夹。有人可以帮助我吗? 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>
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
.假设您的活动的布局 xml 称为
activity_main.xml
而您的过渡可绘制文件称为transition.xml
。
In the root layout of your activity_main.xml
:在您的
activity_main.xml
的根布局中:
<LinearLayout
...
id="@+id/main_layout"
background="@drawable/transition">
<Button
id="@+id/start_transition_button"
... />
...
In MainActivity.java
:在
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这是一篇关于它的好帖子: https : //proandroiddev.com/transitiondrawable-small-gems-of-the-android-framework-4dcdd3c83319
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.