考虑这个 DialogFragment:
public class RollTriggerDialog extends DialogFragment{
private ProgressDialog _dialog;
int _progress;
public Handler _progressHandler;
public RollTriggerDialog() {
// empty
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme());
_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
_dialog.setProgress(0);
_progressHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (_progress >= 100) {
_dialog.dismiss();
} else {
_progress++;
_dialog.incrementProgressBy(1);
_progressHandler.sendEmptyMessageDelayed(0,100);
}
}
};
//_progressHandler.sendEmptyMessage(0); <- This uncommented would start the progress
return _dialog;
}
}
它只是一个带有处理程序的水平进度条,一旦处理程序收到一条消息,进度条就会从 0 变为 100。
如果我想自己从活动中触发 sendEmptyMessage,我总是会收到空指针异常:
public class MainActivity extends FragmentActivity {
private RollTriggerDialog mRollTriggerDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
mRollTriggerDialog = new RollTriggerDialog();
mRollTriggerDialog.show(fm, "addDiceDialog_tag");
((RollTriggerDialog)fm.findFragmentByTag("addDiceDialog_tag"))._progressHandler.sendEmptyMessage(0); // <--- NPE HERE!
}
}
如果在 dialogFragment 中取消了 sendEmptyMessage 行的注释,并且注释了主活动中带有 NPE 的行;应用程序运行。该调用有什么问题?
请注意,这是整个代码,除了清单和布局文件。