2016-04-26 94 views
0

我希望myImageView能够在屏幕内的任意位置找到自己的位置,而不用将文本视图移开。我在另一个线程中发现了这个代码,但我无法使其工作。随机位置上的Imageview

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); 
+0

'Math.random()'是你的朋友。 – rekire

+0

这不是问题所在。问题是,我不知道使用什么方法将imageview放置在某个位置。 –

+0

我刚刚用我在另一个线程中发现的最新代码更新了主帖。根据他们这个代码应该工作,但由于某种原因,它不适合我。 –

回答

0

您可以在一定范围内以编程方式给出保证金,也可以使用设备宽度或高度作为范围。在运行时检查setting margin dynamically的链接,get screen dimension

+0

看起来很有帮助,但请将相关部分提供给您的答案。目前这只是一个链接唯一的答案。 – rekire

0

我想先得到编程器件尺寸然后设置图像视图宽度&高度

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); 
+0

如果您已经知道您的电话已弃用,为什么不提供其他电话? – rekire

+0

我试过你的解决方案,但我还没有能够解决问题。我尝试过使用setX和setY,但是我无法使它工作。这是代码: –

+0

@StephanRogers你得到的错误? –