簡體   English   中英

以編程方式將多個圖像添加到 LinearLayout

[英]Adding multiple Images to LinearLayout programmatically

我正在嘗試將多個 ImageView 添加到 LinearLayout。 LinearLayout 是在 xml 中定義的,但我正在嘗試使用代碼創建 ImageViews。 到目前為止,即使我嘗試多次添加視圖,我的代碼也只是在中間制作了一張圖像。 這是我的主要方法:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout lay = (LinearLayout)findViewById(R.id.layout);
    ImageView[] views = new ImageView[10];
    for (int i=0;i<10;i++){
        views[i] = new ImageView(this);
        views[i].setImageResource(R.drawable.redeight);
        lay.addView(views[i]);
    }
}
}

這是xml:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/layout"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

 </LinearLayout>

在你的 for 循環中試試這個

ImageView iv = new ImageView(this);
ViewGroup.LayoutParams params = iv.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
params.width = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.redeight);

views[i] = iv;
lay.addView(iv);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM