【问题标题】:Imageview on a random position [duplicate]随机位置上的 Imageview [重复]
【发布时间】:2016-08-20 16:56:29
【问题描述】:

我希望 myImageView 将自己定位在屏幕内随机位置的某个位置,而不会将文本视图推开。我在另一个线程中找到了这段代码,但我无法让它工作。

 myImageView = (ImageView) findViewById(R.id.myImageView);
        LinearLayout game = (LinearLayout)findViewById(R.id.game);

        int width = game.getWidth();
        int height = game.getHeight();

        random = new Random();

        int x = width;
        int y = height;

        int imageX = random.nextInt(x-50)+50;
        int imageY = random.nextInt(y-100)+100;

        myImageView.setX(imageX);
        myImageView.setY(imageY);

【问题讨论】:

  • Math.random() 是你的朋友。
  • 这不是问题。问题是我不知道使用什么方法将图像视图放置在某个位置。
  • 我刚刚用我在另一个线程中找到的最新代码更新了主帖。根据他们的说法,这段代码应该可以工作,但由于某种原因它对我不起作用。

标签: java android


【解决方案1】:

您可以在特定范围内以编程方式提供边距,您可以使用设备宽度或高度作为范围。在运行时检查setting margin dynamicallyget screen dimension 的链接。

【讨论】:

  • 看起来很有帮助,但请将相关部分放在您的答案中。目前这只是一个链接的答案。
【解决方案2】:

我认为首先以编程方式获取设备大小,然后设置图像视图的宽度和高度

WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

听到你得到宽度和高度现在设置图像视图大小

android.view.ViewGroup.LayoutParams layoutParams =myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);

如果您仍然无法更改其大小,请尝试将其放入 LinearLayout 并使用布局参数操作 imageView 大小:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
myImageView.setLayoutParams(layoutParams);

【讨论】:

  • 如果您已经知道自己的电话已被弃用,为什么不提供替代电话?
  • 我已经尝试过您的解决方案,但我还没有解决问题。我试过使用 setX 和 setY 但我无法让它工作。这是代码:
  • @StephanRogers 你得到什么错误??
  • 我没有收到任何错误,但有 50% 的时间图像视图本身位于屏幕之外。我将代码添加到主帖中。
  • @StephanRogers 获取设备宽度和高度然后设置图像视图宽度和高度
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多