2017-12-30 62 views
3

프로그래밍 방식으로 생성되고 화면의 임의의 위치에 있지만 화면 크기를 초과하지 않는 10 개의 버튼이 포함 된 활동을 만들려고합니다.화면 크기를 초과하지 않고 무작위로 버튼을 생성합니다.

나는 그렇게했지만 대부분의 버튼이 화면 크기를 초과했습니다 (나는 그것을 볼 수 없었습니다).

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear); 
    Random rnd = new Random(); 

    DisplayMetrics displaymetrics = new DisplayMetrics(); 
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); 
    int height = displaymetrics.heightPixels; 
    int width = displaymetrics.widthPixels; 

    for(int x = 0;x<10;x++) { 

     Button btn = new Button(this); 

     int Xpoistion = rnd.nextInt(width - 100) + 100; 
     int Yposition = rnd.nextInt(height - 100) + 100; 

     btn.setX(Xpoistion); 
     btn.setY(Yposition); 

     btn.setText(x +")"+width + "," + height + " | " + Xpoistion + "," + Yposition); 

     linearLayout.addView(btn); 

    } 

그래서 높이와 너비에서 "화면의 한계"를 만들려고하고 있지만 어떤 이유로 그것을 이해할 수 없습니다.

나는 Xposition과 Yposition을 많이 사용했지만 나에게는 아무런 효과가없는 것 같습니다.

도움을 주셔서 대단히 감사드립니다.

+0

랜덤 값에 100을 추가하는 이유는 무엇입니까? 이렇게하면 100과 displayWidth resp 사이의 버튼의 왼쪽/위쪽 위치가 표시됩니다. 100 및 displayHeight. 그리고 거기에 배치 된 버튼은 오른쪽/아래로 화면을 벗어날 것입니다. – Ridcully

+0

@Ridcully 방금 그걸 가지고 놀았어요, 많은 옵션을 시도했지만 아무 것도 작동하지 않습니다. – user2561521

답변

1

이미 설명한대로 RelativeLayout을 사용해야합니다. 그러나 당신의 논리는 약간 결함이 있습니다, 당신은 버튼을 화면에 표시하지 않도록 보장하기 위해 변수를 설정해야합니다. 나는이 여전히 끝낼 수있는 버튼이 중복 때문에 해결책이 아니라 이미 당신에

int height = displaymetrics.heightPixels; 
    int width = displaymetrics.widthPixels; 
    int buttonWidth = 150; 
    int buttonHeigh = 40; 
    int max_x_val = width - buttonWidth; 
    int max_y_val = heigth - buttonHeigh; // Edited here 

    for(int x = 0;x<10;x++) { 

     Button btn = new Button(this); 

     int Xpoistion = rnd.nextInt(max_x_val - buttonWidth) + buttonWidth; 
     int Yposition = rnd.nextInt(max_y_val - buttonHeigh) + buttonHeigh; 

     btn.setX(Xpoistion); 
     btn.setY(Yposition); 
     btn.setWidth(buttonWidth); 
     btn.setHeight(buttonHeigh); 
     btn.setText(x +")"+width + "," + height + " | " + Xpoistion + "," + Yposition); 

     relativeLayout.addView(btn); 
     Log.d("Debug","Xpos =" + Xpoistion); 
     Log.d("Debug","Ypos =" + Yposition); 
    } 

을 코드의 비트를 추가

여전히 비트를 얻을 수 일부 버튼이 최근 편집 이것은 우리가 화면의 전체 치수를 가지고 있기 때문에 발생합니다. 우리가 필요로했던 것은 단지 Relative Layout의 치수뿐이었습니다. 상단에있는 파란색 막대는 그것이 안되었을 때 측정에 포함되었습니다. 그러나이 오류가 불가능 더 해결하기 까다로운하지만 조금, 조금 구글과 충분한 도움을 찾을 것입니다

편집 : 내 초기 생각은 btn.setX()setY() 그 픽셀에 Button의 중심,하지만 할 것을 그것은 그 같은 픽셀 버튼의 시작을 표시, 그래서 나는 단지로 임의 화 기능을 변경했다 : 나는 다음과 같은 샘플을 쓴 중복 해결하려면

int Xposition = rnd.nextInt(width - buttonWidth); 
int Yposition = rnd.nextInt(height - buttonHeight); 

다음을

// Create dummy class for holding coordinates 
public class ButtonCordinates{ 

public int x; 
public int y; 

public ButtonCordinates(int x, int y) { 
    this.x = x; 
    this.y = y; 
} 
} 

//In MainActivity class create a array for holding coordinates 
ButtonCoordinates [] buttonsCoordinates = new ButtonCoordinates [10];  

int x = 0; 
while(x < 10) { 

    int Xposition = rnd.nextInt(width - buttonWidth); 
    int Yposition = rnd.nextInt(height - buttonHeight); 

    ButtonCoordinates buttonCoords = new ButtonCoordinates (Xposition,Yposition); 

    if(!coordinatesFree(buttonCoords,buttonHeight,buttonWidth)){ 
    // Get another chance 
    continue; 
    } 

    Button btn = new Button(this); 
    btn.setX(Xposition); 
    btn.setY(Yposition); 

    btn.setWidth(buttonWidth); 
    btn.setHeight(buttonHeight); 
    btn.setText(Xposition+";"+Yposition); 

    buttonsCoordinatesArray[x++] = buttonCoords; 

    linearLayout.addView(btn); 
    Log.d("Debug","Xpos =" + Xposition); 
    Log.d("Debug","Ypos =" + Yposition); 
} 

// Method that prevents overlapping 
private boolean coordinatesFree(ButtonCoordinates newButton, int buttonHeight, int buttonWidth){ 

    for(ButtonCoordinates existingButton : buttonsCoordinatesArray){ 
     if(existingButton == null){ 
      // First button ever 
      return true; 
     } 

     boolean f1 = existingButton.x + buttonWidth <= newButton.x; 
     boolean f2 = existingButton.y + buttonHeight <= newButton.y; 
     boolean f3 = existingButton.x - buttonWidth >= newButton.x; 
     boolean f4 = existingButton.y - buttonHeight >= newButton.y; 

     if(!f1 && !f2 && !f3 && !f4){ 
      return false; 
     } 

    } 
    return true; 
} 
+0

감사! 나는 지금 겹쳐진 것을 알아낼 것이다! 당신은 끝내줍니다 :) – user2561521

+1

@ user2561521 max_y_val 변수가 업데이트되었습니다. 나는 그녀에게'너비'를 사용하고있었습니다. 너의 것을 잘 업데이트 해주세요. – Greggz

+0

정말 고마워요 !!!!! – user2561521

1

버튼을 절대 값으로 배치하려면 LinearLayout 대신 RelativeLayout을 사용해야합니다.

편집 : 방금 참조를 찾았습니다. here을 찾을 수 있습니다.

+0

고마워요! 나는 그것을 볼 것이다! – user2561521