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

我想放置一个可绘制的对话框标题栏。 我尝试了以下内容:

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资源),但他们没有工作。

Solutions Collecting From Web of "如何将图标放入自定义对话框的标题中"

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

不知道为什么这个工程。 🙂

这是解决scheme

 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(); } 

即你在构造函数中准备你的窗口特征,然后在onStart中设置具体的资源。

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

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

这是解决scheme。 按照食谱,你会有你的图标! 注意:顺序是非常重要的… … –

  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职位。

把这个静态方法放在你喜欢的工具类中:

 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

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

即在调用dialog.show()完成后我的情况..谢谢.. 🙂