注:以下内容来自第四章
一、定时更新Activity背景图
需要用到定时器用法:Timer + TimerTask
布局
<?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:id="@+id/constraintLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg1080" tools:context=".MyActivity"> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="66dp" android:layout_marginEnd="16dp" android:layout_marginBottom="100dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0" app:srcCompat="@drawable/gu" /> </androidx.constraintlayout.widget.ConstraintLayout>
代码
package com.dzh.review; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.os.Bundle; import java.util.Timer; import java.util.TimerTask; public class MyActivity extends AppCompatActivity { private int idx = 0; //图片序号 private ConstraintLayout layout; //布局 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); layout = (ConstraintLayout) findViewById(R.id.constraintLayout); int[]resIds = new int[]{R.drawable.bg1080,R.drawable.bg1080_2}; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { layout.setBackgroundResource(resIds[idx]); if(idx < resIds.length - 1)idx++; else idx = 0; } }); } }; timer.schedule(task,3000,5000); } }
说明:
Android规定只有主线程才能更新UI,在TimerTask线程中是不能直接更新UI的,但可调用runOnUIThread方法将一个Runnable子线程任务放到主线程中执行
二、创建Acticity选项菜单
步骤:
- 创建菜单资源
- 重写onCreatOptionsMenu方法——创建选项菜单
- 重写onOptionsItemSelected方法——为菜单项添加选中事件
完整代码: