使用预先设计的线性布局动态添加 ImageView

Dynamically adding ImageView using pre-designed linear layouts

我正在开发一个需要在屏幕的特定部分动态添加图像的应用程序。在 运行 应用程序之前将线性布局放置在特定位置是否是个好主意,这样每当 运行 时间需要新的 ImageView 时,我都可以动态地将它添加到它的预置-设计的线性布局?

1.Use LinearLayout 作为根 xml 布局

2.Add LinearLayout.LayoutParamsImageView

3.Add ImageViewLinearLayout

你可以试试这个。

// weight of LinearLayout
int weight = 1;
// LinearLayout you find in your xml code 
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.your_linearlayout);
// LinearLayout LayoutParams ,add width 、height 、weight
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, weight);
// ImageView
ImageView imageView = new ImageView(this);
// ImageView use setImageResource
imageView.setImageResource(R.mipmap.ic_launcher);
// ImageView use setLayoutParams
imageView.setLayoutParams(layoutParams);
// add view to LinearLayout
linearLayout.addView(imageView);

编辑

  • 使用LinearLayout.LayoutParams

    layoutParams.gravity = Gravity.LEFT;
    
  • 使用LinearLayout

    linearLayout.setGravity(Gravity.CENTER);
    
  • LinearLayoutxml代码中使用

    android:gravity="left"