我有一个使用 TabLayout 和 Fragments 的应用程序,但是我的初始登录屏幕是标准 Activity。当我从登录屏幕显示警报对话框时,该对话框的外观与我从 fragment 内部显示警报对话框时完全不同。
从登录屏幕
从 fragment 内部
我用来显示alertDialog的代码是以下类
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.widget.Button;
import android.widget.TextView;
class AlertDialogManager {
private AlertDialog alertDialog;
private Context mContext;
public void showAlertDialog(final Activity activity, String title, String message, Boolean status, final Boolean finishOnClose) {
// Set our context correctly based on what was passed in activity
mContext = (activity.getParent()!=null) ? mContext = activity.getParent() : activity;
// Create our alertDialog Builder
alertDialog = new AlertDialog.Builder(mContext).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
if(status != null) alertDialog.setIcon((status) ? R.drawable.icon_check : R.drawable.icon_alert);
// Setting OK Button
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// if the user passed in TRUE for the finishOnClose param - we call try onBackPressed first and if that fails, call finish()
if (finishOnClose) {
try {
activity.onBackPressed();
} catch (Exception e) {
activity.finish();
}
}
}
});
// Showing Alert Message
alertDialog.show();
}
}
要在 Activity 中显示一个,我使用以下命令:
// At the top of my activity I declare
private final AlertDialogManager alertDialog = new AlertDialogManager();
// Then where I want to show one I use this
alertDialog.showAlertDialog(MyActivity.this, "Title", "Message", false, false);
要在 fragment 中显示一个,我使用以下命令:
// At the top of my fragment I declare
private final AlertDialogManager alertDialog = new AlertDialogManager();
alertDialog.showAlertDialog(getActivity(), "Title", "Message", false, false);
任何人都可以解释为什么我在从 Activity 与 Fragment 调用时会在对话框中看到 2 个完全不同的“主题”吗?我被难住了。
谢谢!!!
最佳答案
您支持的旧 API 版本是什么?因为从 API 11 开始您就可以使用 AlertDialog 构建。如果您支持旧版本,则必须设置主题。
示例:
ContextThemeWrapper theme;
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
theme = new ContextThemeWrapper( context, android.R.style.Theme_Holo_Light_Dialog_NoActionBar );
}
else {
theme= new ContextThemeWrapper( context, android.R.style.Theme_Light_NoTitleBar );
}
AlertDialog.Builder builder = new AlertDialog.Builder(theme);
希望这有帮助。
关于Android:AlertDialog 在 fragment 中看起来不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38616131/