IT

Android : 태블릿에 세로 및 가로를 허용하지만 휴대 전화에서 세로를 강제로 설정 하시겠습니까?

lottoking 2020. 5. 19. 08:16
반응형

Android : 태블릿에 세로 및 가로를 허용하지만 휴대 전화에서 세로를 강제로 설정 하시겠습니까?


태블릿을 세로 및 가로 (sw600dp 이상)로 표시하고 싶지만 휴대 전화는 세로로만 제한됩니다. 조건부로 방향을 선택할 수있는 방법을 찾을 수 없습니다. 어떤 제안?


다음은 resourcessize 한정자를 사용하는 좋은 방법 입니다.

이 bool 자원을 res / values에 bools.xml 또는 무엇이든 (파일 이름은 중요하지 않음)으로 넣으십시오.

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

이것을 res / values-sw600dp 및 res / values-xlarge에 넣으십시오.

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

Android Studio에서 이러한 디렉토리 및 파일을 추가하는 데 도움 이되는 추가 답변참조하십시오 .

그런 다음 활동의 onCreate 메소드에서 다음을 수행 할 수 있습니다.

    if(getResources().getBoolean(R.bool.portrait_only)){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

최소 너비 방향으로 600dp 이상인 기기 또는 Android 3.2 이전 버전 기기 (기본적으로 태블릿)에서 x-large 는 센서 및 사용자 잠금 회전 등에 따라 정상적으로 작동합니다 . 다른 모든 것 (전화, 거의)은 초상화 일뿐입니다.


이 방법으로 먼저 장치의 화면 크기를 얻을 수 있습니다.

if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
    Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();

}
else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
    Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();

} 
else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
    Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
}
else {
    Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
}

그런 다음에 따라 방향을 설정하십시오

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

내가 한 방법은 다음과 같습니다 ( http://androidblogger.blogspot.com/2011/08/orientation-for-both-phones-and-tablets.html에서 영감을 얻음 ).

AndroidManifest.xml에서 세로와 가로 사이에서 변경하려는 각 활동에 대해 (screenSize를 추가했는지 확인하십시오-필요하지 않았습니다!) 여기에서 화면 방향을 설정할 필요는 없습니다. :

android:configChanges="keyboardHidden|orientation|screenSize"

각 활동에 추가하는 방법 :

public static boolean isXLargeScreen(Context context) {
    return (context.getResources().getConfiguration().screenLayout
    & Configuration.SCREENLAYOUT_SIZE_MASK)
    >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
} 

및 : (이 방법을 재정의하지 않으면 방향을 변경할 때 앱이 onCreate ()를 호출합니다)

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

    if (!isXLargeScreen(getApplicationContext()) ) {            
        return; //keep in portrait mode if a phone      
    }

    //I set background images for landscape and portrait here
}

각 활동의 onCreate ()에서 :

if (!isXLargeScreen(getApplicationContext())) { //set phones to portrait; 
   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);            
}
else {
  //I set background images here depending on portrait or landscape orientation 
}

내가 알아낼 수없는 유일한 것은 가로에서 세로로 또는 그 반대로 전환 할 때 앱이 레이아웃 파일을 변경하도록하는 방법입니다. 나는 대답이 위의 링크와 비슷한 것을하고 있다고 가정하지만, 나에게 도움이되지는 못했습니다. 모든 데이터가 삭제되었습니다. 그러나 세로 및 가로에 동일한 레이아웃 파일이있는 간단한 응용 프로그램이 있으면 작동합니다.


허용 된 답변 보충

Android Studio에서 다음 단계를 수행 하여 파일에 res/values-sw600dpres/values-large디렉토리 를 추가 할 bools.xml있습니다.

값 -sw600dp

우선 프로젝트 탭의 탐색기에서 프로젝트 (Android 대신) 필터를 선택하십시오.

여기에 이미지 설명을 입력하십시오

그런 다음 app/src/main/res디렉토리를 마우스 오른쪽 단추로 클릭하십시오 . 새로 작성 > Android 자원 디렉토리를 선택하십시오 .

선택 작은 화면 폭을 한 후 누르 >> 버튼을 누릅니다.

여기에 이미지 설명을 입력하십시오

입력 600작은 화면 폭. 디렉토리 이름이 자동으로 생성됩니다. 네라고하세요.

여기에 이미지 설명을 입력하십시오

그런 다음 새로 만든 values-sw600dp파일을 마우스 오른쪽 버튼으로 클릭하십시오 . 새로 작성 > 값 자원 파일을 선택 하십시오 . bools이름을 입력 하십시오.

값이 큰

values-large디렉토리를 추가하는 것은 Android 3.2 이전 버전 (API 레벨 13)을 지원하는 경우에만 필요합니다. 그렇지 않으면이 단계를 건너 뛸 수 있습니다. values-large디렉토리에 해당합니다 values-sw600dp. (에 values-xlarge해당합니다 values-sw720dp.)

To create the values-large directory, follow the same steps as above, but in this case choose Size rather than Smallest Screen Width. Select Large. The directory name will be automatically generated.

여기에 이미지 설명을 입력하십시오

Right click the directory as before to create the bools.xml file.


Following Ginny's answer, I think the most reliable way to do it is as follows:

As described here, put a boolean in resources sw600dp. It must have the prefix sw otherwise it won't work properly:

in res/values-sw600dp/dimens.xml

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

in res/values/dimens.xml

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

Then make a method to retrieve that boolean:

public class ViewUtils {
    public static boolean isTablet(Context context){
        return context.getResources().getBoolean(R.bool.isTablet);
    }
}

And a base activity to extend from the activities where you want this behaviour:

public abstract class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (!ViewUtils.isTablet(this)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }
}

So each activity would extend BaseActivity:

public class LoginActivity extends BaseActivity //....

Important: even if you extend from BaseActivity, you must add the line android:configChanges="orientation|screenSize" to each Activity in your AndroidManifest.xml:

    <activity
        android:name=".login.LoginActivity"
        android:configChanges="orientation|screenSize">
    </activity>

Well, this is a bit of late but, here is an XML-Only but a hack solution which does not recreate an activity as setRequestedOrientation does if has to change orientation:

https://stackoverflow.com/a/27015879/1281930


Old question I know. In order to run your app always in portrait mode even when orientation may be or is swapped etc (for example on tablets) I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

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

    }

Works like a charm!

NOTICE: Change this.activity by your activity or add it to the main activity and remove this.activity ;-)

If you want to do the opposite, you must change the code to landscape (but I think it is clear how to this).


Unfortunately, using the method setRequestedOrientation(...) will cause the activity to restart, so even if you call this in the onCreate method it will go through the activity lifecycle and then it will recreate the same activity in the requested orientation. So at @Brian Christensen's answer you should consider that the activity code might be called twice, this could have bad effects (not only visual, but also at network requests, analytics, etc.).

Furthermore, to set the configChanges attribute in the manifest is in my opinion a big trade-off, which could take massive refactoring cost. Android Devs are not recommending to change that attribute.

Finally, trying to set the screenOrientation somehow different (to avoid the restarting problem) is impossible, statically impossible due to the static manifest which can't be changed, programmatically it is only possible to call that method in the already started activity.

Summary: In my opinion, @Brian Christensen suggestion is the best trade-off, but be aware of the restarting activity issue.


Other solutions didn't work for me. I still had some weird orientation problem with dialogs and recreation issues. My solution was to extend the Activity, forcing it as portrait in manifest.

Example:

public class MainActivityPhone extends MainActivity {}

manifest.xml:

        <activity
        android:screenOrientation="portrait"
        android:name=".MainActivityPhone"
        android:theme="@style/AppTheme.NoActionBar" />

in splashcreen activity:

    Intent i = null;
    boolean isTablet = getResources().getBoolean(R.bool.is_tablet);
    if (!isTablet)
        i = new Intent(this, MainActivityPhone.class);
    else
        i = new Intent(this, MainActivity.class);
    startActivity(i);

참고URL : https://stackoverflow.com/questions/9627774/android-allow-portrait-and-landscape-for-tablets-but-force-portrait-on-phone

반응형