IT이야기

Android 폰에서 방향 확인

cyworld 2022. 5. 28. 10:14
반응형

Android 폰에서 방향 확인

Android 폰이 가로 또는 세로인지 어떻게 확인할 수 있습니까?

하기 위해 의 [Resources]에서할 수 .Configuration★★★★★★★★★★★★★★★★★★:

getResources().getConfiguration().orientation;

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

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

자세한 내용은 Android Developer에서 확인할 수 있습니다.

일부 디바이스에서 getResources().getConfiguration(). 오리엔테이션을 사용하면 잘못된 정보를 얻을 수 있습니다.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-land ★★★★★★★★★★★★★★★★★」res/values-port다음 내용을 포함합니다.

res/values-land/syslog.xml:

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

res/values-port/values.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";
    }
}

다음은 Hackbod와 Martjin이 추천한 화면 방향을 얻는 방법 코드 스니펫 데모입니다.

§ 방향 변경 시 트리거:

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

§ hackbod의 추천에 따라 현재 오리엔테이션을 취득한다:

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

① 현재 화면 방향을 얻기 위한 대체 솔루션이 있다 Martijn 솔루션을 따른다:

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

주의: &과 ❸를 모두 사용해 보았습니다만, RealDevice(NexusOne SDK 2.3) Orientation에서는 방향이 틀립니다.

솔루션 ①을 사용하면, 보다 선명하고 심플하고, 매력적으로 동작하는 화면 방향을 얻을 수 있습니다.

★반환 방향을 주의 깊게 확인하여 예상대로 정확한지 확인(물리 디바이스 사양에 따라 제한될 수 있음)

도움이 됐으면 좋겠는데

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;
        }

대부분의 답변이 게시된 후 시간이 경과하여 일부에서는 사용되지 않는 메서드와 상수를 사용하고 있습니다.

다음 메서드와 상수를 더 이상 사용하지 않도록 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

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;
    }       
}

Android SDK를 사용하면 다음과 같은 사실을 알 수 있습니다.

getResources().getConfiguration().orientation

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

/** @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;
}

이는 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;
}

단순한 두 줄 코드

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

이 코드는 오리엔테이션 변경이 적용된 후에 작동될 수 있다고 생각합니다.

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

Activity.onConfigurationChanged(Configuration newConfig) 함수를 덮어쓰고 setContentView를 호출하기 전에 새 오리엔테이션에 대해 알림을 받으려면 방향인 newConfig를 사용합니다.

getRotationv()를 사용하는 것은 도움이 되지 않는다고 생각합니다.http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation()은 화면의 회전을 자연스러운 방향에서 되돌리기 때문입니다.

그래서 '자연스러운' 방향을 모르면 회전은 무의미해요.

더 쉬운 방법을 찾아냈어

  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

이 사람에게 문제가 있다면 말씀해 주시겠습니까?

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

   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;
    }

현악기에는 오리엔티온이 있다.

이것을 할 수 있는 많은 방법들이 있다, 이 코드 조각은 나에게 효과가 있다.

 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. xml 레이아웃을 2개 작성합니다(세로 및 가로).
  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;
}

또, 오늘날에는, 다음과 같이 명시적인 오리엔테이션을 체크할 합당한 이유가 적다는 것에 주의할 필요가 있습니다.getResources().getConfiguration().orientationAndroid 7/API 24+에서 도입된 멀티 윈도우 지원으로 인해 레이아웃이 어느 방향으로든 상당히 엉망이 될 수 있습니다.사용을 검토하는 것이 좋다<ConstraintLayout>사용 가능한 너비 또는 높이에 따라 다른 레이아웃과 함께 사용 중인 레이아웃을 판별하기 위한 다른 방법(예를 들어 특정 조각이 액티비티에 첨부되어 있는지 여부)도 있습니다.

다음 항목을 사용할 수 있습니다(여기에 따라).

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;
}

언급URL : https://stackoverflow.com/questions/2795833/check-orientation-on-android-phone

반응형