Android에서 레이아웃의 방향 변경을 감지하는 방법은 무엇입니까?
방금 방향 변경 기능을 구현했습니다. 예를 들어 레이아웃이 세로에서 가로로 (또는 그 반대로) 변경 될 때. 방향 변경 이벤트가 언제 끝났는지 어떻게 알 수 있습니까?
은 OrientationEventListener
작동하지 않았다. 레이아웃 방향 변경 이벤트에 대한 알림을 받으려면 어떻게해야합니까?
Activity 의 onConfigurationChanged 메소드를 사용하십시오 . 다음 코드를 참조하십시오.
@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();
}
}
또한 적절한 android : configChanges 를 포함 할 매니페스트 파일의 요소는 아래 코드를 참조하십시오.
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
참고 : Android 3.2 (API 레벨 13) 이상에서는 기기가 세로 방향과 가로 방향 사이를 전환 할 때 '화면 크기'도 변경됩니다. 따라서 API 레벨 13 이상으로 개발할 때 방향 변경으로 인한 런타임 재시작을 방지하려면 API 레벨 13 이상에 대해 android : configChanges = "orientation | screenSize"를 선언해야합니다 .
이것이 당신을 도울 것입니다 ... :)
에서 레이아웃로드를 들어 레이아웃 토지 폴더 수단을 당신은 두 개의 별도의 레이아웃을 가지고 당신은 확인해야합니다 setContentView
으로 onConfigurationChanged
하는 방법.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.yourxmlinlayout-land);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.yourxmlinlayoutfolder);
}
}
레이아웃이 하나만있는 경우이 메서드에서 setContentView를 만들 필요가 없습니다. 간단히
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
onConfigurationChanged 후 모든 번들을 저장하는 방법을 보여주고 싶었습니다.
수업 직후 새 번들을 만듭니다.
public class MainActivity extends Activity {
Bundle newBundy = new Bundle();
Next, after "protected void onCreate" add this:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
onSaveInstanceState(newBundy);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
onSaveInstanceState(newBundy);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
}
If you add this all your crated classes into MainActivity will be saved.
But the best way is to add this in your AndroidManifest:
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
use this method
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
Toast.makeText(getActivity(),"PORTRAIT",Toast.LENGTH_LONG).show();
//add your code what you want to do when screen on PORTRAIT MODE
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
Toast.makeText(getActivity(),"LANDSCAPE",Toast.LENGTH_LONG).show();
//add your code what you want to do when screen on LANDSCAPE MODE
}
}
And Do not forget to Add this in your Androidmainfest.xml
android:configChanges="orientation|screenSize"
like this
<activity android:name=".MainActivity"
android:theme="@style/Theme.AppCompat.NoActionBar"
android:configChanges="orientation|screenSize">
</activity>
Override activity's method onConfigurationChanged
Create an instance of OrientationEventListener
class and enable it.
OrientationEventListener mOrientationEventListener = new OrientationEventListener(YourActivity.this) {
@Override
public void onOrientationChanged(int orientation) {
Log.d(TAG,"orientation = " + orientation);
}
};
if (mOrientationEventListener.canDetectOrientation())
mOrientationEventListener.enable();
I just want to propose another alternative that will concern some of you, indeed, as explained above:
android:configChanges="orientation|keyboardHidden"
implies that we explicitly declare the layout to be injected.
In case we want to keep the automatic injection thanks to the layout-land and layout folders. All you have to do is add it to the onCreate:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
getSupportActionBar().hide();
} else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
getSupportActionBar().show();
}
Here, we display or not the actionbar depending on the orientation of the phone
If accepted answer doesn't work for you, make sure you didn't define in manifest file:
android:screenOrientation="portrait"
Which is my case.
In case this is of use to some newer dev's because its not specified above. Just to be very explicit:
You need two things if using onConfigurationChanged:
An
onConfigurationChanged
method in your Activity ClassSpecify in your manifest which configuration changes will be handled by your
onConfigurationChanged
method
The manifest snippet in the above answers, while no doubt correct for the particular app that manifest belongs to, is NOT exactly what you need to add in your manifest to trigger the onConfigurationChanged method in your Activity Class. i.e. the below manifest entry may not be correct for your app.
<activity name= ".MainActivity" android:configChanges="orientation|screenSize"/>
In the above manifest entry, there are various Android actions for android:configChanges=""
which can trigger the onCreate in your Activity lifecycle.
This is very important - The ones NOT Specified in the manifest are the ones that trigger your onCreate and The ones specified in the manifest are the ones that trigger your onConfigurationChanged
method in your Activity Class.
So you need to identify which config changes you need to handle yourself. For the Android Encyclopedically Challenged like me, I used the quick hints pop-out in Android Studio and added in almost every possible configuration option. Listing all of these basically said that I would handle everything and onCreate will never be called due to configurations.
<activity name= ".MainActivity" android:configChanges="screenLayout|touchscreen|mnc|mcc|density|uiMode|fontScale|orientation|keyboard|layoutDirection|locale|navigation|smallestScreenSize|keyboardHidden|colorMode|screenSize"/>
Now obviously I don't want to handle everything, so I began eliminating the above options one at a time. Re-building and testing my app after each removal.
Another important point: If there is just one configuration option being handled automatically that triggers your onCreate (You do not have it listed in your manifest above), then it will appear like onConfigurationChanged
is not working. You must put all relevant ones into your manifest.
I ended up with 3 that were triggering onCreate originally, then I tested on an S10+ and I was still getting the onCreate, so I had to do my elimination exercise again and I also needed the |screenSize
. So test on a selection of platforms.
<activity name= ".MainActivity" android:configChanges="screenLayout|uiMode|orientation|screenSize"/>
So my suggestion, although I'm sure someone can poke holes in this:
Add your
onConfigurationChanged
method in your Activity Class with a TOAST or LOG so you can see when its working.Add all possible configuration options to your manifest.
Confirm your
onConfigurationChanged
method is working by testing your app.Remove each config option from your manifest file one at a time, testing your app after each.
Test on as large a variety of devices as possible.
Do not copy/paste my snippet above to your manifest file. Android updates change the list, so use the pop-out Android Studio hints to make sure you get them all.
I hope this saves someone some time.
My onConfigurationChanged
method just for info below. onConfigurationChanged
is called in the lifecycle after the new orientation is available, but before the UI has been recreated. Hence my first if
to check the orientation works correctly, and then the 2nd nested if
to look at the visibility of my UI ImageView also works correctly.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
pokerCardLarge = findViewById(R.id.pokerCardLgImageView);
if(pokerCardLarge.getVisibility() == pokerCardLarge.VISIBLE){
Bitmap image = ((BitmapDrawable)pokerCardLarge.getDrawable()).getBitmap();
pokerCardLarge.setVisibility(pokerCardLarge.VISIBLE);
pokerCardLarge.setImageBitmap(image);
}
}
}
참고URL : https://stackoverflow.com/questions/5726657/how-to-detect-orientation-change-in-layout-in-android
'developer tip' 카테고리의 다른 글
내 데이트에 회의록을 추가하는 방법 (0) | 2020.08.24 |
---|---|
URI의 마지막 경로 세그먼트를 얻는 방법 (0) | 2020.08.24 |
PHP에서 두 날짜 사이의 시간 계산 (0) | 2020.08.24 |
MySQL IF NOT NULL, 다음 표시 1, 그렇지 않으면 표시 0 (0) | 2020.08.24 |
AngularJS-필터의 빈 결과에 대한 자리 표시 자 (0) | 2020.08.24 |