效果图:
res/layout/main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/backgroud" android:id="@+id/layout"> </LinearLayout>
在res/drawable/下放置四张图片(img01.jpg、img02.jpg、img03.jpg、img04.jpg)
MainActivity:
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; public class MainActivity extends Activity { private ImageView[] img=new ImageView[4];//声明一个ImageView组件的数组 private int[] imagePath=new int[]{ //声明并初始化一个保存访问图片的数组 R.drawable.img01,R.drawable.img02,R.drawable.img03,R.drawable.img04 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取XML文件中定义的线性布局管理器 LinearLayout linearLayout =(LinearLayout)findViewById(R.id.layout); for (int i = 0; i < imagePath.length; i++) { img[i]=new ImageView(this);//创建一个ImageView组件 img[i].setImageResource(imagePath[i]);//为ImageView组件指定要显示的图片 img[i].setPadding(5,5,5);//设置ImageView的内边距 LayoutParams params=new LayoutParams(253,148);//设置图片宽度和高度 img[i].setLayoutParams(params);//为ImageView组件设置布局参数 linearLayout.addView(img[i]);//将ImageView组件添加到布局管理器中 } } }
转载请注明出处:http://www.jb51.cc/article/p-drouinnp-bay.html 原文链接:https://www.f2er.com/xml/297006.html