2016-04-26 96 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你得到的錯誤? –