我试图在android生成一个自定义的对话框。我像下边这样创建我的对话框:
dialog = new Dialog(this);
dialog.setContentView(R.layout.my_dialog);
除了对话框的title,其他的都很好。就算我不设置对话框的title,当对话框弹出的时候仍然有一个空白的地方。
有什么方法可以隐藏掉这个空白的地方么?
我用 AlertDialog试了,但是看起来布局设置不是很正确:
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.map_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);
// dialog = new Dialog(this);
// dialog.setContentView(R.layout.map_dialog);
dialog = builder.create();
((TextView) dialog.findViewById(R.id.nr)).setText(number);
如果我用这个代码,我会在最后一行得到一个空指针异常。对话框不是空的,所以我尝试查找的TextView不存在。
如果在我使用对话框的构造函数部分取消注释的部分,一切都很好,除了我的对话框布局上的title部分。
你需要使用到 AlertDialog。
在这么短的总结,你的代码就像是从官网中复制的一样。那需要一个自定义布局文件,给它一些基本的文本和图标,然后创建它。然后显示它,再用alertDialog.show()
AlertDialog.Builder builder;
AlertDialog alertDialog;
Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater)
mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
(ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
当从零开始创建一个对话框的话,FEATURE_NO_TITLE起作用,像这样:
Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
但是创建AlertDialog的话它不起作用(或者使用Builder),因为它已经禁用了标题和在内部使用自定义。
我已经检查了SDK资源,我认为它无法起作用。所以为了把底部的空白删除,我认为唯一的解决方法就是从零创建一个自定义的对话框,直接通过使用对话框类。
同样,也可以用一个样式,例如在styles.xml:
<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>
然后
Dialog dialog = new Dialog(context, R.style.FullHeightDialog);
你可以通过下边的代码去掉title,这个对话框的名字是我的
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
where dialog is name of my dialog .