切换到横向布局时,应用程序崩溃
我在应用程序中设置横向模式时遇到问题。
我有一个/ res文件夹,其中包含布局文件夹和layout-land文件夹
layout -----main.xml layout-land -----main.xml
我的/layout-land/main.xml包含与/layout/main.xml不同的UI元素。 当用户切换到横向模式时,如何正确映射每个布局,反之亦然?
当用户切换到横向模式时,我基本上显示全屏ImageView。 ImageView将从互联网上下载图像并显示它。 切换回肖像,应该回到我的肖像模式,它具有不同的UI组件集。
当我切换到横向模式时,我遇到了崩溃:
因为我无法获得身份certificate:
chartImageViewLandscape = (ImageView) this.findViewById(R.id.chartImageViewLandscape);
chartImageViewLandscape位于/layout-land/main.xml中
我怎样才能得到这个参考?
Sheehan,关于onRetainNonConfigurationInstance(),下面是我正在为正在进行的应用程序做的事情。 虽然我觉得我过于复杂,但我觉得有一种更简单的方式; 但是,这对我来说效果很好:
所以在我的活动类“RotationMenu.java”中:
private Object catcher; //lots of non-related code here //directoryList is a returned list of selected directories, that I wish to //retain in the event of an orientation state change. String[] directoryList = new String[arrayList.size()]; arrayList.toArray(directoryList); //here, I set the class Object catcher to the directoryList catcher = directoryList; //rest of non-related code //this method is called when the orientation changes (for me, //when I open my Droid's hardware keyboard) public Object onRetainNonConfigurationInstance() { //If I've entered anything into my catcher Object, it will be kept //across orientation changes. final Object data = catcher; return data; }
现在,在我的onCreate(Bundle savedInstanceState)方法中:
//We retrieve the stored Object and cast it to a String array final Object recipient = (String[]) getLastNonConfigurationInstance(); //in case the state changes again before the code that sets the directories is run catcher = recipient; //if there was any stored data, we can now reinstate the list adapter where the //directoryList was originally being used. if(recipient != null) { returnedDirectories.setAdapter(new ArrayAdapter( this.getBaseContext(), R.layout.simple_list_item_small, (String[])recipient)); }
同样,这就是我目前正在做的事情。 如果有人知道更有效的方法,一定要评论。 🙂
究竟是什么问题?
你在两个布局中定义了android:orientation
吗? 除此之外,别无他法。 Android会自行切换。
如果您有不同的UI组件,您可能仍希望在两种布局中声明它们,以便对findViewById
任何调用都不会使您的应用程序崩溃。 只需进行布局,使其不显示(例如在FrameLayout中,在图像后面)
如果您更喜欢手动执行此操作,则需要在清单中放置android:configChanges="orientation"
并实现onConfigurationChanged
这来自AdMob活动,有更多参数,例如screenSize适用于Android 3.2+
转到Android“manifest”xml文件,确保“活动”部分中包含以下内容:
android:configChanges="orientation|screenSize|keyboardHidden"
清单的最终“活动”部分应类似于以下内容: