背景切换效果显示
1、资源目录drawable放5张PNG的图片,大小为960×540(b1.png、b2.png、b3.png、b4.png、b5.png);
2、布局 activity_main.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal"
android:background="@drawable/b1"
android:id="@+id/bkt"
tools:context="com.ccc.cwh.csdn003.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="136dp"
android:orientation="vertical">
<Button
android:id="@+id/button3"
android:layout_width="279dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="演示按钮"
android:layout_weight="0.03" />
<Button
android:id="@+id/button4"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="改变背景"
android:onClick="onSetBK"
android:layout_weight="0.01" />
</LinearLayout>
</LinearLayout>
3、MainActivity 文件
public class MainActivity extends Activity {
int nbk = 0; // 计数
// 5个PNG的图片
public int[] bkIds = new int[]{R.drawable.b1, R.drawable.b2, R.drawable.b3, R.drawable.b4, R.drawable.b5};
LinearLayout bk; // 背景 ID
private Drawable bg_1; // 背景资源
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bk = (LinearLayout) findViewById(R.id.bkt);
bg_1 = getResources().getDrawable(bkIds[0]);
}
// 点击改变背景图
public void onSetBK(View v) {
nbk = nbk + 1;
if (nbk > 4) nbk = 0;
Drawable bg_2 = getResources().getDrawable(bkIds[nbk]);
TransitionDrawable bktd = new TransitionDrawable(new Drawable[]{bg_1, bg_2});
bk.setBackgroundDrawable(bktd);
bktd.startTransition(1500);
bg_1 = bg_2;
}
}