我正在编写一个自定义视图,从RelativeLayout扩展,我想以编程方式调整它,我该怎么办?
自定义视图类是这样的:
public ActiveSlideView(Context context, AttributeSet attr){
super(context, attr);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(inflater != null){
inflater.inflate(R.layout.active_slide, this);
}
Run Code Online (Sandbox Code Playgroud)
smi*_*icz 241
如果您错过了布局的高度或宽度,Android会抛出异常.而不是创建一个新的LayoutParams对象使用视图的原始对象,这样保留所有其他设置参数:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)
her*_*rtD 120
this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, theSizeIWant));
Run Code Online (Sandbox Code Playgroud)
问题解决了!
注意:请务必使用父布局LayoutParams.我的是LinearLayout.LayoutParams!
Sil*_*ria 58
这对我有用:
ViewGroup.LayoutParams params = layout.getLayoutParams();
params.height = customHeight;
layout.requestLayout();
Run Code Online (Sandbox Code Playgroud)
Dan*_*eld 43
对于它的价值,假设您想要在设备无关像素(dp)中调整视图的大小: -
您需要使用一个名为的方法applyDimension,该方法是类的成员,TypedValue可以将像素转换为dps.所以,如果我想将高度设置为150dp(比方说) - 那么我可以这样做:
float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) someLayout.getLayoutParams();
params.height = (int) pixels;
someLayout.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)
表达式:getResources().getDisplayMetrics()获取屏幕密度/分辨率
Phi*_*hil 38
在 Kotlin 中,您可以使用ktx 扩展:
yourView.updateLayoutParams {
height = <YOUR_HEIGHT>
}
Run Code Online (Sandbox Code Playgroud)
以下是来自@herbertD的上述解决方案的更通用版本:
private void resizeView(View view, int newWidth, int newHeight) {
try {
Constructor<? extends LayoutParams> ctor = view.getLayoutParams().getClass().getDeclaredConstructor(int.class, int.class);
view.setLayoutParams(ctor.newInstance(newWidth, newHeight));
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
尝试这个:
...
View view = inflater.inflate(R.layout.active_slide, this);
view.setMinimumWidth(200);
Run Code Online (Sandbox Code Playgroud)
我用这种方法来增加自定义视图的宽度
customDrawingView.post(new Runnable() {
@Override
public void run() {
View view_instance = customDrawingView;
android.view.ViewGroup.LayoutParams params = view_instance
.getLayoutParams();
int newLayoutWidth = customDrawingView
.getWidth()
+ customDrawingView.getWidth();
params.width = newLayoutWidth;
view_instance.setLayoutParams(params);
screenWidthBackup = params.width;
}
});
Run Code Online (Sandbox Code Playgroud)
对于 Kotlin 并使用 dp 单位:
myView.updateLayoutParams {
val pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, context.resources.displayMetrics)
height = pixels.toInt()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
233989 次 |
| 最近记录: |