我正在为我的相对布局添加一个视图,其周围有16dp填充
View blackView = new View(RestaurantActivity.this);
blackView.setMinimumHeight(height);
blackView.setMinimumWidth(width);
blackView.setBackgroundColor(Color.BLACK);
blackView.setAlpha(0.5f);
rl.addView(blackView);
并且这个视图也有填充,但我希望它填满整个屏幕并忽略填充,如何以编程方式完成?
由于
修改
我试过这个
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)blackView.getLayoutParams();
float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (-16*scale + 0.5f);
params.rightMargin = dpAsPixels;
params.leftMargin = dpAsPixels;
params.bottomMargin = dpAsPixels;
blackView.setLayoutParams(params);
但得到了这个错误
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.james.duss.ResturantActivity$1.onClick(ResturantActivity.java:156)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
工作代码:
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)blackView.getLayoutParams();
float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (-16*scale + 0.5f);
params.rightMargin = dpAsPixels;
params.leftMargin = dpAsPixels;
params.bottomMargin = dpAsPixels;
blackView.setLayoutParams(params);
在RelativeLayout
:android:clipToPadding="false"
答案 1 :(得分:0)
以dp而非像素获取填充的更好,更清晰的解决方案如下:
您必须将填充存储在资源文件中(即dimens.xml
),因此您只需调用:
int padding = getResources().getDimensionPixelOffset(R.dimen.padding);
它为您进行转换。然后,您可以将填充设置为所需的视图,例如:
mPicImageView.setPadding(padding, padding, padding, padding);