怎么样将一个view图层设置成根据手机屏幕高宽动态设置样式
时间: 2024-05-02 15:23:24 浏览: 140
可以使用 Android 中的布局文件来动态设置 View 的样式。具体步骤如下:
1. 在布局文件中,使用百分比单位设置 View 的宽高,例如:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/my_view"
android:layout_width="50%"
android:layout_height="50%"
android:background="@android:color/black" />
</RelativeLayout>
```
上述代码中,View 的宽高都设置为屏幕宽高的 50%。
2. 在 Activity 或 Fragment 中,获取屏幕宽高并动态设置 View 的宽高,例如:
```
View myView = findViewById(R.id.my_view);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int screenWidth = displayMetrics.widthPixels;
int screenHeight = displayMetrics.heightPixels;
float viewWidth = screenWidth * 0.5f;
float viewHeight = screenHeight * 0.5f;
myView.setLayoutParams(new RelativeLayout.LayoutParams((int) viewWidth, (int) viewHeight));
```
上述代码中,首先获取屏幕宽高,然后根据屏幕宽高计算出 View 的宽高,最后动态设置 View 的宽高。
这样,就可以根据手机屏幕高宽动态设置 View 的样式了。
阅读全文
相关推荐


















