我试着通过点击按钮来切换背景的颜色。它显示了初始颜色(蓝色),当我点击它会变成下一种颜色(红色)。当我再次点击时,它会变回蓝色,并迅速变为红色,而不是我的第三种颜色(白色)。我已经在colors.xml文件中定义了颜色,并创建了一个名为transition.xml的可绘制资源来转换。
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>
1条答案
按热度按时间brvekthn1#
transitiondrawable仅支持两层
transitiondrawable是一个可以在两个可绘制资源之间交叉淡入淡出的可绘制对象。