使用Dialog创建dialog时,即使不设置标题,标题部分依然存在,而使用AlertDialog不存在这个问题。不过在一些手机上会存在一个bug:虽然没有标题栏,但是标题栏所占的扣减还是存在的,大约有50dp左右的高度。下面是一个设置自定义对话框的demo。
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
>
<Button
android:id="@+id/take_picture_btn"
android:text="@string/take_picture"
android:layout_width="100dp"
android:layout_height="40dp"
android:gravity="center"
/>
<Button
android:id="@+id/take_video_btn"
android:layout_width="100dp"
android:layout_height="40dp"
android:text="@string/take_video"
/>
</LinearLayout>
java代码:
private void createControlPanel() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.control_panel, null);
Button takePictureBtn = (Button) layout.findViewById(R.id.take_picture_btn);
takePictureBtn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// Does some things.
}
});
final Button takeVideoBtn = (Button) layout.findViewById(R.id.take_video_btn);
takeVideoBtn.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// Does ....
}
});
builder.setView(layout); //这句非常重要
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) { //点击返回键时,需要做出的反应
// Does ...
return true;
}
return false;
}
});
dialog = builder.create();
}
设置Dialog的参数,需要在show()方法后面设置:
dialog.show()
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.alpha = 0.8f; //透明度
params.width = 460; //dialog宽度
params.y = height -20; //显示位置,默认居中显示
controlPanel.getWindow().setAttributes(params);