写出Android 动态设置控件的高度和宽度,俩个imageView分别是a和b放到一个linearlayout,其中b竖屏时隐藏横屏时显示,动态设置俩们俩的宽高占满linearlayout
时间: 2024-02-29 15:52:08 浏览: 68
好的,以下是实现的代码:
```java
// 获取控件
ImageView a = findViewById(R.id.imageView_a);
ImageView b = findViewById(R.id.imageView_b);
LinearLayout linearLayout = findViewById(R.id.linearLayout);
// 设置b竖屏时隐藏
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
b.setVisibility(View.GONE);
} else {
b.setVisibility(View.VISIBLE);
}
// 动态设置控件宽高
LinearLayout.LayoutParams layoutParamsA = (LinearLayout.LayoutParams) a.getLayoutParams();
LinearLayout.LayoutParams layoutParamsB = (LinearLayout.LayoutParams) b.getLayoutParams();
layoutParamsA.width = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParamsA.height = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParamsB.width = LinearLayout.LayoutParams.MATCH_PARENT;
layoutParamsB.height = LinearLayout.LayoutParams.MATCH_PARENT;
a.setLayoutParams(layoutParamsA);
b.setLayoutParams(layoutParamsB);
```
这段代码可以实现以下功能:
1. 获取控件a、b和linearLayout的引用;
2. 判断当前屏幕方向,若为竖屏则将b设置为隐藏,若为横屏则将b设置为显示;
3. 动态设置控件a、b的宽高为MATCH_PARENT,以占满linearLayout的宽高。
阅读全文