Programming

안드로이드 폰의 방향 확인

procodes 2020. 2. 23. 12:07
반응형

안드로이드 폰의 방향 확인


Android 전화가 가로 또는 세로인지 확인하려면 어떻게합니까?


검색 할 자원을 판별하는 데 사용되는 현재 구성은 자원 Configuration오브젝트 에서 사용 가능 합니다.

getResources().getConfiguration().orientation;

값을보고 방향을 확인할 수 있습니다.

int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // In landscape
} else {
    // In portrait
}

자세한 정보는 Android 개발자 에서 찾을 수 있습니다 .


일부 장치에서 getResources (). getConfiguration (). orientation을 사용하면 잘못됩니다. 우리는 처음에 http://apphance.com에서이 접근 방식을 사용했습니다 . Apphance의 원격 로깅 덕분에 다양한 장치에서 볼 수 있었고 조각화가 그 역할을하는 것을 알았습니다. HTC Desire HD에서 이상한 초상화와 사각형 (?!)을 번갈아 보았습니다.

CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
CONDITION[17:37:15.898] screen: rotation: 90
CONDITION[17:37:21.451] screen: rotation: 0
CONDITION[17:38:42.120] screen: rotation: 270 orientation: square

방향을 전혀 바꾸지 않거나

CONDITION[11:34:41.134] screen: rotation: 0
CONDITION[11:35:04.533] screen: rotation: 90
CONDITION[11:35:06.312] screen: rotation: 0
CONDITION[11:35:07.938] screen: rotation: 90
CONDITION[11:35:09.336] screen: rotation: 0

반면에 width ()와 height ()는 항상 정확합니다 (창 관리자가 사용하므로 더 좋습니다). 가장 좋은 아이디어는 항상 너비 / 높이 검사를 수행하는 것입니다. 당신이 순간에 대해 생각한다면, 이것은 당신이 원하는 것입니다-너비가 높이 (세로)보다 작거나 반대 (가로) 또는 같은지 (사각형)인지 알고 싶습니다.

그런 다음이 간단한 코드로 귀결됩니다.

public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

이 문제를 해결하는 또 다른 방법은 디스플레이의 올바른 반환 값에 의존하지 않고 Android 리소스를 사용하는 것입니다.

파일 생성 layouts.xml폴더에있는 res/values-landres/values-port다음 내용을 :

res / values-land / layouts.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">true</bool>
</resources>

res / values-port / layouts.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">false</bool>
</resources>

소스 코드에서 다음과 같이 현재 방향에 액세스 할 수 있습니다.

context.getResources().getBoolean(R.bool.is_landscape)

전화의 현재 방향을 지정하는 완전한 방법 :

    public String getRotation(Context context){
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
           switch (rotation) {
            case Surface.ROTATION_0:
                return "portrait";
            case Surface.ROTATION_90:
                return "landscape";
            case Surface.ROTATION_180:
                return "reverse portrait";
            default:
                return "reverse landscape";
            }
        }

치어 빈 응 우옌


다음은 hackbodMartijn 이 화면 방향을 얻는 방법을 권장하는 코드 스 니펫 데모입니다 .

❶ 방향 변경시 트리거 :

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
        int nCurrentOrientation = _getScreenOrientation();
    _doSomeThingWhenChangeOrientation(nCurrentOrientation);
}

hack hackbod가 권장하는 현재 방향을 얻으십시오 .

private int _getScreenOrientation(){    
    return getResources().getConfiguration().orientation;
}

screen 현재 화면 방향을 얻는 대안 솔루션이 있습니다. Mar Martijn 솔루션을 따르십시오 .

private int _getScreenOrientation(){
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        return display.getOrientation();
}

참고 : ❷ & implement을 모두 시도했지만 RealDevice (NexusOne SDK 2.3) 방향에서는 잘못된 방향을 반환합니다.

★ 따라서 솔루션을 사용 하여 더 유리한 화면 방향을 얻으려면 선명하고 간단하며 매력처럼 작동하는 것이 좋습니다 .

★ 정확한 방향 복귀를 확인하여 예상대로 정확한지 확인하십시오 (물리적 장치 사양에 따라 제한 될 수 있음)

도움이 되길 바랍니다.


int ot = getResources().getConfiguration().orientation;
switch(ot)
        {

        case  Configuration.ORIENTATION_LANDSCAPE:

            Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
        break;
        case Configuration.ORIENTATION_PORTRAIT:
            Log.d("my orient" ,"ORIENTATION_PORTRAIT");
            break;

        case Configuration.ORIENTATION_SQUARE:
            Log.d("my orient" ,"ORIENTATION_SQUARE");
            break;
        case Configuration.ORIENTATION_UNDEFINED:
            Log.d("my orient" ,"ORIENTATION_UNDEFINED");
            break;
            default:
            Log.d("my orient", "default val");
            break;
        }

getResources().getConfiguration().orientation올바른 방법으로 사용하십시오 .

다른 유형의 풍경, 장치가 일반적으로 사용하는 풍경 및 다른 풍경을주의해야합니다.

여전히 관리 방법을 이해하지 못합니다.


이러한 답변의 대부분이 게시되고 일부 사용이 중단되어 메소드와 상수가 사용 된 후 어느 정도 시간이 지났습니다.

이 메소드와 상수를 더 이상 사용하지 않도록 Jarek의 코드업데이트했습니다 .

protected int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    Point size = new Point();

    getOrient.getSize(size);

    int orientation;
    if (size.x < size.y)
    {
        orientation = Configuration.ORIENTATION_PORTRAIT;
    }
    else
    {
        orientation = Configuration.ORIENTATION_LANDSCAPE;
    }
    return orientation;
}

이 모드 Configuration.ORIENTATION_SQUARE는 더 이상 지원되지 않습니다.

나는 그것을 사용하는 방법을 제안하는 방법과 달리 테스트 한 모든 장치에서 신뢰할 수 있음을 발견했습니다. getResources().getConfiguration().orientation


런타임시 화면 방향을 확인하십시오.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();        
    }
}

그것을하는 또 다른 방법이 있습니다.

public int getOrientation()
{
    if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
    { 
        Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
        t.show();
        return 1;
    }
    else
    {
        Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
        t.show();
        return 2;
    }       
}

안드로이드 SDK는 이것을 잘 알 수 있습니다.

getResources().getConfiguration().orientation

방향 변경이 적용된 후이 코드가 작동 할 수 있다고 생각합니다.

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

setContentView를 호출하기 전에 새 방향에 대한 알림을 받으려면 Activity.onConfigurationChanged (Configuration newConfig) 함수를 대체하고 newConfig, orientation을 사용하십시오.


http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation () "Root"에서 화면 회전을 반환 하므로 getRotationv ()를 사용하면 도움이되지 않는다고 생각합니다. 정위.

"자연"방향을 모르면 회전은 의미가 없습니다.

더 쉬운 방법을 찾았어요

  Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  if(width>height)
    // its landscape

이 사람에게 문제가 있는지 알려주십시오.


사용자가 세로 방향을 설정했는지 여부에 관계없이 API 28에서 2019 년에 테스트했으며 다른 오래된 답변 과 비교하여 최소한의 코드로 올바른 방향을 제공합니다.

/** @return The {@link Configuration#ORIENTATION_SQUARE}, {@link Configuration#ORIENTATION_PORTRAIT}, {@link Configuration#ORIENTATION_LANDSCAPE} constants based on the current phone screen pixel relations. */
private int getScreenOrientation()
{
    DisplayMetrics dm = context.getResources().getDisplayMetrics(); // Screen rotation effected

    if(dm.widthPixels == dm.heightPixels)
        return Configuration.ORIENTATION_SQUARE;
    else
        return dm.widthPixels < dm.heightPixels ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
}

내가 알고있는 오래된 포스트. 방향이 무엇이든 또는 교환되는 것이 무엇이든간에 나는 세로 및 가로 기능이 장치에서 어떻게 구성되는지 알 필요없이 장치를 올바른 방향으로 설정하는 데 사용되는이 기능을 설계했습니다.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

매력처럼 작동합니다!


이 방법으로

    int orientation = getResources().getConfiguration().orientation;
    String Orintaion = "";
    switch (orientation)
    {
        case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
        case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
        case Configuration.ORIENTATION_PORTRAIT:  Orintaion = "Portrait"; break;
        default: Orintaion = "Square";break;
    }

문자열에서 당신은 Oriantion이


이 작업을 수행하는 방법에는 여러 가지가 있습니다.이 코드는 저에게 효과적입니다.

 if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
             // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                      // landscape
        }

간단하고 쉬운 :)

  1. 2 가지 XML 레이아웃 만들기 (예 : 세로 및 가로)
  2. Java 파일에서 다음을 작성하십시오.

    private int intOrientation;
    

    onCreate방법과 이전에 setContentView쓰기 :

    intOrientation = getResources().getConfiguration().orientation;
    if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
        setContentView(R.layout.activity_main);
    else
        setContentView(R.layout.layout_land);   // I tested it and it works fine.
    

이 솔루션이 쉬운 것 같아요

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}

이러한 oneplus3와 같은 모든 전화를 오버레이입니다

public static boolean isScreenOriatationPortrait(Context context) {
         return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
         }

다음과 같이 올바른 코드 :

public static int getRotation(Context context){
        final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

        if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180){
            return Configuration.ORIENTATION_PORTRAIT;
        }

        if(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270){
            return Configuration.ORIENTATION_LANDSCAPE;
        }

        return -1;
    }

또한 Android 7 / API 24+에 도입 된 다중 창 지원이 레이아웃 중 일부를 혼란스럽게 만들 수 getResources().getConfiguration().orientation있기 때문에 레이아웃 이유로 인해 명시 적 방향을 확인해야 할 이유가 적다는 점도 주목할 가치가 있습니다. 정위. 더 나은 사용을 고려 하고, 대체 레이아웃을 사용할 수 너비 또는 높이에 따라 당신의 활동에 부착되는 특정 조각의 예를 들어, 사용되는 레이아웃 존재를 결정하기위한 다른 트릭과 함께, 또는하지.<ConstraintLayout>


이것을 사용할 수 있습니다 ( here ).

public static boolean isPortrait(Activity activity) {
    final int currentOrientation = getCurrentOrientation(activity);
    return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}

public static int getCurrentOrientation(Activity activity) {
    //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
    final Display display = activity.getWindowManager().getDefaultDisplay();
    final int rotation = display.getRotation();
    final Point size = new Point();
    display.getSize(size);
    int result;
    if (rotation == Surface.ROTATION_0
            || rotation == Surface.ROTATION_180) {
        // if rotation is 0 or 180 and width is greater than height, we have
        // a tablet
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a phone
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
    } else {
        // if rotation is 90 or 270 and width is greater than height, we
        // have a phone
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a tablet
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
        }
    }
    return result;
}

간단한 두 줄 코드

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // do something in landscape
} else {
    //do in potrait
}

참고 URL : https://stackoverflow.com/questions/2795833/check-orientation-on-android-phone



반응형