我想设置自定义对话框的宽度以包裹内容
但它总是填满屏幕的所有宽度
我已经测试过这个
android.view.WindowManager.LayoutParams params = mydialog.getWindow().getAttributes();
params.width = android.view.WindowManager.LayoutParams.WRAP_CONTENT;
mydialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
and that
mydialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
我也很难解决这个问题,最后找到了更好的方法来解决这个问题。
这是解决方法。在你的代码中
mydialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
这不起作用,因为 ProgressDialog 的默认布局具有左和右边距的 match_parent。要调整 ProgressDialog 的大小,您需要一个自定义视图,如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@android:drawable/dialog_holo_light_frame"
android:layout_gravity="center_horizontal"
android:id="@+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/progressBar"/>
<TextView
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:layout_marginRight="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:gravity="center"
android:id="@+id/message"/>
</LinearLayout>
并在显示 ProgressDialog 后对其进行充气。膨胀自定义视图后,使用 GlobalLayoutListener 获取自定义视图的宽度并设置布局宽度。
mDialog.show();
final Window window = mDialog.getWindow();
window.setContentView(R.layout.custom_progress_dialog); // this is the above code
final LinearLayout dialogContainer = (LinearLayout) window.findViewById(R.id.container);
TextView message = (TextView) window.findViewById(R.id.message);
message.setText("Loading . . .");
dialogContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = dialogContainer.getWidth();
window.setLayout(width, WindowManager.LayoutParams.WRAP_CONTENT);
dialogContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)