android studio的for循环五张照片
时间: 2023-07-07 07:40:20 浏览: 109
好的,以下是使用 Android Studio 实现在界面上展示五张照片的 for 循环代码:
1. 在布局文件中添加 ImageView 控件(如果已经存在,可以跳过这一步):
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/image1"/>
</LinearLayout>
```
2. 在 Java 代码中使用 for 循环来更新 ImageView 的 src 属性:
```
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
int[] imageIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5};
for (int i = 0; i < imageIds.length; i++) {
imageView.setImageResource(imageIds[i]);
try {
Thread.sleep(1000); // 间隔 1 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们首先在 onCreate() 方法中获取 ImageView 控件的引用,然后定义一个整型数组来存储五张照片的资源 ID。接着,我们使用 for 循环来遍历这个数组,每次更新 ImageView 的 src 属性为数组中的一个元素,并且让线程暂停 1 秒钟以便我们能够看到照片的变化。注意,为了避免在主线程中阻塞 UI,我们使用了 try-catch 语句来捕获 InterruptedException 异常。
阅读全文
相关推荐


















