问题描述
有时候我想在应用启动时显示一个对话框。为此,我创建了一个名为LoginDialog的自定义对话框,并且使用了Application类java。但是,我在显示此对话框时遇到了麻烦。对于一个我不能调用getsupportfragmentmanager()或类似的东西。另外,代码还回答了loginDialog没有show方法,我认为这是AppCompatDialogFragment类的标准操作。任何有关解决此问题的技巧都将受到赞赏!
代码:
public class ApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = getSharedPreferences("Settings",MODE_PRIVATE);
SharedPreferences.Editor sEditor = sharedPreferences.edit();
if (sharedPreferences.getInt("EmailVer",0) == 5) {
showDialog();
}
Log.i("Abertura","onCreate fired");
}
private void showDialog() {
LoginDialog loginDialog = new LoginDialog();
loginDialog.show(get);
}
}
解决方法
也许尝试在Activity类中显示一个对话框?您可以加载SharedPreferences并检查是否要在Application类中显示对话框,但要在Activity中显示对话框。看起来像这样:
ApplicationClass:
import android.app.Application;
import android.util.Log;
public class ApplicationClass extends Application
{
private boolean showDialog;
public boolean getShowDialog()
{
return showDialog;
}
@Override
public void onCreate()
{
super.onCreate();
Log.i("MyTag","onCreate Application");
// check if You want dialog. Main logic here
showDialog = true;
}
}
MainActivity:
import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (((ApplicationClass) getApplication()).getShowDialog()) //get application and show dialog if `showDialog` is true
{
Log.i("MyTag","Show dialog");
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Message")
.show();
}
else
{
Log.i("MyTag","Do not show dialog");
}
}
}