我想创建一个带有自定义布局的Dialog
。我希望width
与手机屏幕的宽度相同,height
与WRAP_CONTENT
相同。
以下是我的尝试:
Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_share);
dialog.setCanceledOnTouchOutside(true);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(dialog.getWindow().getAttributes());
layoutParams.width = width;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.BOTTOM;
dialog.getWindow().setAttributes(layoutParams);
问题是dialog
只占屏幕宽度的90%左右,dialog
的左侧和右侧有一些余量。如何让它完全填满手机的宽度?
答案 0 :(得分:2)
公认的解决方案既简单又有效,但您也可以尝试以下解决方案来达到要求。
步骤1:创建Dialog类的子类,因为您想要创建自定义对话框。
public class ARProgressDialog extends Dialog
{
Activity context;
public ARProgressDialog(Context context,int id) {
// TODO Auto-generated constructor stub
super(context,id);
this.context=(Activity) context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.progress_dialog); // Your custom layout
// BELOW CODE IS USED TO FIND OUT WIDTH OF ANY DEVICE
DisplayMetrics displaymetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
// BELOW CODE IS USED TO SET WIDHT OF DIALOG
LinearLayout layout = (LinearLayout)findViewById(R.id.dialogLinearLayout); // this is the id of your parent layout defined in progress_dialog.xml
LayoutParams params = layout.getLayoutParams();
params.width = width;
layout.setLayoutParams(params);
...// add your remaining code
}
}
第2步:显示对话框。
ARProgressDialog dialog=new ARProgressDialog(this,R.style.MyTheme);
dialog.show();
第3步:MyTheme.xml的代码
<style name="MyTheme" parent="android:Theme.Holo.Dialog">
<item name="android:windowBackground">#00000000</item>
<item name="android:backgroundDimEnabled">true</item>
</style>
答案 1 :(得分:1)
这可能对您有所帮助:
dialog.setContentView(R.layout.my_custom_dialog);
dialog.getWindow().setBackgroundDrawable(null);
或者您可以尝试style
这样的课程:
<style name="Theme_Dialog" parent="android:Theme.Holo.Dialog">
...
<item name="android:windowMinWidthMajor">100%</item>
<item name="android:windowMinWidthMinor">100%</item>
</style>