使用静态方法从视图 class 调用对话框
Call to dialog from View class with static method
我有问题。
我想从视图 class 调用对话框。我使用 public 方法。这是静态的。但是当我使用 ... = new Dialog(getInstance());
或类似的然后应用程序到达那里时,它停止并且日志猫告诉我参数 context
是 NULL。
我尝试了几件事,但没有。始终为 NULL。静态方法在 Activity class.
恢复。当我尝试将上下文放入静态方法时,程序说我是 NULL。
如果我可以在 View class.
中调用,我不需要 View 的强制调用
我把代码放上来获取更多信息。
Class Activity:
public class Control_Playing extends Activity{
private static Control_Playing instance;
public static Control_Playing getInstance() {
if(instance == null)
instance = new Control_Playing();
return instance;
}
....
public static void runEmptyBox() {
Dialog dialog = new Dialog(getInstance());
dialog.setTitle("asdf");
dialog.setContentView(R.layout.dialog_1);
TextView text = (TextView)dialog.findViewById(R.id.tv2);
text.setText("asdf");
dialog.show();
}
Class 查看:
....
Control_Playing.runEmptyBox();
....
手动创建 Activity 是不好的,它不会工作,所以这是不好的,也是您问题的原因。
public static Control_Playing getInstance() {
if(instance == null)
instance = new Control_Playing();
return instance;
}
您需要为其提供 Activity
上下文!
public static void showDialog(Context context){
if(!(context instanceof Activity)){
throw new new IllegalStateException("Context should be an activity");
}
Dialog dialog = new Dialog((Activity) context);
...
}
不要在 Activity 之间共享同一个对话框,你应该有一个静态构造方法并在每个 activity 中保留一个单独的实例,否则你将面临新的问题!
我有问题。
我想从视图 class 调用对话框。我使用 public 方法。这是静态的。但是当我使用 ... = new Dialog(getInstance());
或类似的然后应用程序到达那里时,它停止并且日志猫告诉我参数 context
是 NULL。
我尝试了几件事,但没有。始终为 NULL。静态方法在 Activity class.
恢复。当我尝试将上下文放入静态方法时,程序说我是 NULL。 如果我可以在 View class.
中调用,我不需要 View 的强制调用我把代码放上来获取更多信息。
Class Activity:
public class Control_Playing extends Activity{
private static Control_Playing instance;
public static Control_Playing getInstance() {
if(instance == null)
instance = new Control_Playing();
return instance;
}
....
public static void runEmptyBox() {
Dialog dialog = new Dialog(getInstance());
dialog.setTitle("asdf");
dialog.setContentView(R.layout.dialog_1);
TextView text = (TextView)dialog.findViewById(R.id.tv2);
text.setText("asdf");
dialog.show();
}
Class 查看:
....
Control_Playing.runEmptyBox();
....
手动创建 Activity 是不好的,它不会工作,所以这是不好的,也是您问题的原因。
public static Control_Playing getInstance() {
if(instance == null)
instance = new Control_Playing();
return instance;
}
您需要为其提供 Activity
上下文!
public static void showDialog(Context context){
if(!(context instanceof Activity)){
throw new new IllegalStateException("Context should be an activity");
}
Dialog dialog = new Dialog((Activity) context);
...
}
不要在 Activity 之间共享同一个对话框,你应该有一个静态构造方法并在每个 activity 中保留一个单独的实例,否则你将面临新的问题!