【发布时间】:2013-10-18 23:27:27
【问题描述】:
我的 DialogFragments 有一个大问题。
我的 DialogFragments 依赖于服务连接才能正常运行。当用户按下按钮弹出一个对话框时,这是可以的,因为活动在 onServiceConnected() 中绘制按钮,确保服务始终对 DialogFragment 可用。
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Start the service.
Intent gameServiceIntent = new Intent(this, GameService.class);
startService(gameServiceIntent);
bindService(gameServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
...
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// Assign the gameService object to a member variable.
GameActivity.this.gameService = ((GameService.LocalBinder)service).getService();
// Create a button that pops up a dialog.
// The dialog uses MainActivity.getGameService().
...
public GameService getGameService() {
return gameService;
}
...
然后DialogFragment使用游戏服务。
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
this.gameActivity = (GameActivity) getActivity();
gameActivity.getService();
然而,在方向改变时(当用户旋转手机并打开对话框时),当恢复应用程序状态时,Android 在调用 onServiceConnected() 之前调用 DialogFragment.onCreateDialog()。然后当对话框调用 MainActivity.getGameService() 时,我得到一个空指针异常和崩溃。
对于所有其他内置于 onServiceConnected() 的 UI 组件,这也是一个问题。例如,一个 ListView 和一个 TableLayout。 在创建 Dialog 时它们为 null,因为在 onServiceConnected() 之前调用了 onCreateDialog()。
我该如何解决这个问题?!
【问题讨论】:
标签: android android-fragments android-service android-dialog android-dialogfragment