0

考虑这个 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 的行;应用程序运行。该调用有什么问题?

请注意,这是整个代码,除了清单和布局文件。

4

1 回答 1

1

出现NullPointerException是因为findFragmentByTag回报null。解决方案是fm.executePendingTransactions()在您使用该findFragmentByTag方法立即执行该片段事务之前调用(有关详细信息,请参阅此问题)。

此外,Handler引用将null在那个时刻,因此您需要在片段的生命周期方法之一中对其进行初始化,例如onCreate

public static Handler _progressHandler; // should be made static

//...
@Override
public void onCreate(Bundle savedInstanceState) {       
    super.onCreate(savedInstanceState);
    _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);
            }

        }
    };
}
于 2012-10-09T11:49:11.707 回答