如何将图标放入自定义对话框的标题中

我想把一个drawable放到一个对话框标题栏中。 我尝试了以下方法:

final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.some_icon); dialog.setTitle(R.string.my_dialog_title); dialog.setContentView(R.layout.my_dialog_layout); ... 

图标没有显示,但标题向右移动了一点。 看来对话框为drawable保留空间但不绘制它。 我尝试了几个不同的图标(也来自android资源),但没有它们工作。

show() 之后调用setFeatureDrawableResource() show()

不知道为什么会这样。 🙂

这是解决方案

 final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); dialog.setTitle(R.string.my_dialog_title); dialog.setContentView(R.layout.my_dialog_layout); dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.some_icon); dialog.show(); 

如果您希望对话框看起来像一个活动,而不是像下面那样将主题添加到对话框

 final Dialog dialog = new Dialog(this,AlertDialog.THEME_HOLO_LIGHT); 

您还可以像这样扩展Dialog类:

 public class CustomDialog extends Dialog { public CustomDialog(Context context) { super(context); setTitle("Some Title"); requestWindowFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.my_layout); } @Override protected void onStart() { setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.my_icon); super.onStart(); } 

即,您在构造函数中准备窗口function,然后在onStart中设置具体资源。

所以,在主代码中你可以简单地使用:

  CustomDialog cd = new CustomDialog(getActivity()); rd.show(); 

这是解决方案。 按照食谱,你将有你的图标! 注意:订单非常重要……

  final Dialog yourDialog = new Dialog(YourClass.this); yourDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON); //must come BEFORE setContentView yourDialog.setContentView(R.layout.yourDialog_layout); yourDialog.setTitle("Your Title"); yourDialog.setCancelable(true); yourDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.your_icon); //must come AFTER setContentView 

由于SmaïlHammour的post,我让它以不同的方式工作。

将此静态方法放在首选工具类中:

 public static void msgBox( String msg, String title, int type, final Context c){ int theIcon = drawable.ic_dialog_alert; switch(type){ case YourToolClass.CONFIRMATION: theIcon = drawable.ic_menu_help; break; case YourToolClass.INFO: theIcon = drawable.ic_dialog_info; break; case YourToolClass.ALERT: default: } AlertDialog.Builder builder = new AlertDialog.Builder(c); /* Here enters the .setIcon: */ builder.setMessage(msg) .setTitle (title) .setIcon(theIcon); builder.setPositiveButton( "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { /* */ } }); AlertDialog dialog = builder.create(); dialog.show(); } 

要调用:

 YourToolClass.msgBox("the main message goes here", "Test", getBaseContext()); 
 setIcon(R.drawable.image_name) 

调用setFeatureDrawableResource llike

  dialog.show(); dialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.logo_1x); 

即在调用dialog.show()之后在我的情况下工作得很好..谢谢.. 🙂