优雅解决加载dialog 动态设置文字出现空指针解决方案
程序员文章站
2022-05-28 12:21:10
...
public static final long DIALOG_TIME = 100;
Dialog 中设置文字的方法
public void setMessage(String text) {
if (tv_message != null) {
tv_message.setText(text);
handler.removeCallbacksAndMessages(null);
} else {
Bundle bundle = new Bundle();
bundle.putString("text", text);
Message message = new Message();
message.setData(bundle);
message.what = MSG_SET_TEXT;
handler.sendMessageDelayed(message, Constants.DIALOG_TIME);
}
}
常量值 随便写
private static final int MSG_SET_TEXT = 1001;
核心逻辑
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_SET_TEXT:
Bundle data = msg.getData();
String text = "";
if (data != null) {
text = data.getString("text");
}
setMessage(text);
break;
}
}
};
进来直接轮询 为空就发个100ms的延时消息 等待不为空就设置上 并且关闭轮询