如何在运行时动态创建imageviews?

时间:2013-07-18 10:19:40

标签: android android-imageview relativelayout

我正在构建一个Android应用程序,需要创建最多1-4个图像视图,具体取决于我需要在屏幕上显示的图像数量。我写了一个小代码,但它似乎并没有将屏幕分成4个图像视图。在我的情况下,前2个比底部2略大。以下是我的代码我真的不能想到问题是什么

private void CreateScreen()
{
    int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
    int screenWidth = getWindowManager().getDefaultDisplay().getWidth();

    int matrixN = 2;

    int maxWForEachScreen = screenWidth / matrixN;
    int maxHForEachScreen = screenHeight / matrixN;
    RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayoutFullScreen);

    ImageView imgView1 = new ImageView(LiveViewer.this);
    ImageView imgView2 = new ImageView(LiveViewer.this);
    ImageView imgView3 = new ImageView(LiveViewer.this);
    ImageView imgView4 = new ImageView(LiveViewer.this);

    int size = 3;

    if(size >= 3 && size <= 4)
    {
        imgView1.setImageResource(R.drawable.icon);
        imgView2.setImageResource(R.drawable.icon);
        imgView3.setImageResource(R.drawable.icon);
        imgView4.setImageResource(R.drawable.icon);

        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(100, 100);
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(100, 100);
        RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(100, 100);
        RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(100, 100);

        params1.height = maxHForEachScreen/2;
        params1.width = maxWForEachScreen/2;

        params2.height = maxHForEachScreen/2;
        params2.width = maxWForEachScreen/2;

        params3.height = maxHForEachScreen/2;
        params3.width = maxWForEachScreen/2;

        params4.height = maxHForEachScreen/2;
        params4.width = maxWForEachScreen/2;

        params1.setMargins(0, 0, 0, 0);
        params2.setMargins(maxWForEachScreen/2, 0, 0, 0);
        params3.setMargins(0, maxHForEachScreen/2, 0, 0);
        params4.setMargins(maxWForEachScreen/2, maxHForEachScreen/2, 0, 0);

        relativeLayout.addView(imgView1, params1);
        relativeLayout.addView(imgView2, params2);
        relativeLayout.addView(imgView3, params3);
        relativeLayout.addView(imgView4, params4);      
    }
}

1 个答案:

答案 0 :(得分:0)

你可以设置parentLayout的权重等于视图的数量..并设置1作为每个视图的权重...这将使每个视图占用相等的空间..