[英]How to place an icon into the title of a custom dialog
我想把一個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();
}
即,您在構造函數中准備窗口功能,然后在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的帖子,我讓它以不同的方式工作。
將此靜態方法放在首選工具類中:
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()之后在我的情況下工作得很好..謝謝.. :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.