Android – 处理屏幕上的对话方向更改

前端之家收集整理的这篇文章主要介绍了Android – 处理屏幕上的对话方向更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我覆盖了onCreateDialog和onPrepareDialog方法或Dialog类.

我遵循了Reto Meier的专业Android应用程序开发书第5章中的一些例子来拉一些XML数据,然后使用一个对话框来显示信息.

我基本上跟着它,但改变了这些变量以适合我自己的XML模式,如下所示:

@Override
public Dialog onCreateDialog(int id) {
  switch(id) {
    case (SETTINGS_DIALOG) :        
      LayoutInflater li = LayoutInflater.from(this);
      View settingsDetailsView = li.inflate(R.layout.details,null);

      AlertDialog.Builder settingsDialog = new AlertDialog.Builder(this);
      settingsDialog.setTitle("Provisioned Settings");         
      settingsDialog.setView(settingsDetailsView);
return settingsDialog.create();
  }
  return null;
}

@Override
public void onPrepareDialog(int id,Dialog dialog) {
  switch(id) {
    case (SETTINGS_DIALOG) :                  

String afpunText = "  ";

     if(setting.getAddForPublicUserNames() == 1){
      afpunText = "Yes";
     }
     else{
      afpunText = "No";
     }
      String Text = "Login Settings: " + "\n" 
                       + "Password: " + setting.getPassword()  + "\n" 
                       + "Server: " + setting.getServerAddress() + "\n";


      AlertDialog settingsDialog = (AlertDialog)dialog; 
settingsDialog.setTitle(setting.getUserName());

tv = (TextView)settingsDialog.findViewById(R.id.detailsTextView);
if (tv != null)
        tv.setText(Text);

      break;
  }
}

它工作正常,直到我尝试改变屏幕方向,当我这样做onPrepareDialog获取调用,但我得到所有我的变量的空指针异常.

即使我告诉我的活动来忽略清单中的屏幕方向,错误仍然发生.

所以我认为这本书中的例子已经被遗漏了,我需要重写另外一种方法来保存我的变量吗?

我现在添加了以下内容

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  // Save UI state changes to the savedInstanceState.
  // This bundle will be passed to onCreate if the process is
  // killed and restarted.
  savedInstanceState.putString("Username",setting.getUserName());
  savedInstanceState.putString("Password",setting.getPassword());
  savedInstanceState.putString("Server",setting.getServerAddress());

  super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  settings.clear();
  // Restore UI state from the savedInstanceState.
  // This bundle has also been passed to onCreate.
  username = savedInstanceState.getString("Username");
  password = savedInstanceState.getString("Password");
  serveraddress = savedInstanceState.getString("Server");


Settings setting = new Settings(username,password,serveraddress);
addNewSettings(setting);

}

但是我仍然得到空指针异常

解决方法

我没有Reto的书,所以我不能检查代码,但如果书中有错误,可以在Twitter上轻松地与他联系,讨论: http://twitter.com/retomeier

请记住,如果屏幕方向更改,则会重新创建您的活动.这意味着,在新方向重新创建活动后,您最后设置的任何变量(不是静态的)将丢失.

我的猜测是你在这里打了一个NullPointerException:

if(setting.getAddForPublicUserNames() == 1){

如果是这样,很可能某些用户操作将“设置”变量更改为非空值,您需要确保在重新创建活动时再次设置.

存储/检索方向之间的活动状态的最标准方法在此详细说明:Saving Android Activity state using Save Instance State

原文链接:https://www.f2er.com/android/312395.html

猜你在找的Android相关文章