我有一个警告对话框,我想设置宽度和高度取决于我的屏幕设备,而不是像1300,880这样的常数。
如何在非活动类和非片段类中获得宽度和高度?
static abstract class BaseHolder extends RecyclerView.ViewHolder {
.
.
.
LayoutInflater inflater = (LayoutInflater) mViewAction.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDialog = new Dialog(mViewAction.getContext());
mDialogView = inflater.inflate(R.layout.dialog_deletetoken, null);
mDialog.setContentView(mDialogView);
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mDialog.getWindow().setLayout(1300,880);
}发布于 2018-12-16 08:21:28
您无法直接获得组件高度宽度的值,这完全取决于活动生命周期。
您可以将引用传递给非活动类中可用的上下文,并通过该上下文获得结果。
例如,如果您想获得设备屏幕比率或高度/宽度或密度,您可以这样做:
public static int getScreenHeightInDP(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float screenHeightInDP = displayMetrics.heightPixels / displayMetrics.density;
return Math.round(screenHeightInDP);
}编辑
对于您的情况,创建一个像这样的实用程序类,
public class Utility {
public static void setLayout(DialogFragment dialogFragment) {
DisplayMetrics displayMetrics = dialogFragment.getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
if(dialogFragment.getDialog().getWindow()!=null)
dialogFragment.getDialog().getWindow().setLayout(width,height);
}
}https://stackoverflow.com/questions/53800493
复制相似问题