java - 切换到横向布局时应用程序崩溃

标签 java android layout orientation

我在我的应用程序中设置横向模式时遇到问题。

我有一个/res 文件夹,其中包含一个 layout 文件夹和一个 layout-land 文件夹

layout
-----main.xml

layout-land
-----main.xml

我的/layout-land/main.xml 包含与/layout/main.xml 不同的 UI 元素。当用户切换到横向模式时如何正确映射每个布局,反之亦然?

当用户切换到横向模式时,我基本上显示全屏 ImageView。 ImageView 将从 Internet 下载图像并显示它。切换回纵向模式,应该简单地回到我的纵向模式,它有一组不同的 UI 组件。

当我切换到横向模式时发生崩溃:

因为我拿不到id:

chartImageViewLandscape = (ImageView) this.findViewById(R.id.chartImageViewLandscape);

chartImageViewLandscape 在/layout-land/main.xml 中

我如何获得对此的引用?

最佳答案

Sheehan,关于 onRetainNonConfigurationInstance(),下面是我目前正在为我的应用程序做的事情。我觉得我把它过于复杂了,我认为有一种更简单的方法;但是,目前这对我来说效果很好:

所以在我的 Activity 类“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<String>(
        this.getBaseContext(),
        R.layout.simple_list_item_small,
        (String[])recipient));
}

同样,这就是我目前的做法。如果有人知道更有效的方法,一定要发表评论。 :)

关于java - 切换到横向布局时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3638467/

相关文章:

java - JCheckBox 的问题在 Java 的 JList 中检查了切换逻辑

java - 一台mac上是否可以安装两个java SDK?

html - 如何防止表格高度溢出容器div?

java - 如何解决java.lang.RuntimeException : Parcelable encountered IOException writing serializable object

css - 使用 div 而不是表格的基本布局

android - 在 ListActivity android 中添加 ListView 和线性布局

java - 我希望球知道它们位于 JPanel 中的矩形内

java - Android 验证电子邮件凭据

android - 如何跨 Activity 更改背景颜色

android - 在android中使用HttpUrlConnection查询字符串返回Null