【问题标题】:How to create imageviews dynamically on runtime?如何在运行时动态创建图像视图?
【发布时间】:2013-07-18 20:15:13
【问题描述】:

我正在构建一个 android 应用程序,该应用程序需要创建最多 1-4 个图像视图,具体取决于我需要在屏幕上显示的图像数量。我写了一个小代码,但它似乎并没有将屏幕平均划分为 4 个图像视图。就我而言,前两个比下两个大一点。以下是我的代码,我真的想不出问题是什么

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);      
    }
}

【问题讨论】:

  • 尝试使用表格布局或网格布局。
  • 使用getSize(Point) 代替getHeight()getWidth()。它们已被弃用。 maxWForEachScreenmaxHForEachScreen 的整数值是多少?
  • @Vikram 请详细说明一下?
  • 使用相对布局有什么问题,我也看不出使用网格布局有什么意义。 @Vikram 我得到了屏幕宽度和高度的合法值,即 1280 和 720。我认为这与布局参数有关,或者因为根据剩余空间可能是底部 ImageView 适合
  • @Mr.Noob 请看我下面的帖子。

标签: android android-imageview android-relativelayout


【解决方案1】:

您可以将parentLayout的weightsum设置为等于views的数量..并将每个view的权重设置为1...这将使每个views占用相等的空间..

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2015-05-02
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多