需求:界面有时候显示图片的数量未知,需要在代码中动态添加图片。
案例一个ImageView 显示3张图片
方法步骤:
1:布局
<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:id="@+id/ll_group"
android:orientation="vertical"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/viewGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" />
</ScrollView>
</LinearLayout>
2:类
public class MainActivity extends AppCompatActivity {
private LinearLayout contentLlayout;
private ImageView addImg;
private int[] images = {1,2,3};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup);
ImageView[] imageViews = new ImageView[images.length];
for (int i = 0; i < imageViews.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
imageViews[i] = imageView;
imageView.setImageResource(R.drawable.beauty);
group.addView(imageView);
}
}
}
|