【发布时间】:2016-02-11 22:07:20
【问题描述】:
我正在尝试确定屏幕的宽度和高度以在片段中使用它们。
我的片段布局的 id 为 background。
如果在onViewCreated 里面我使用:
background = (RelativeLayout) view.findViewById(R.id.background);
background.post(new Runnable() {
@Override
public void run() {
int width = background.getMeasuredWidth();
int height = background.getMeasuredHeight();
Log.d("askj", width + "+" + height);
}
});
我收到1440+2276
但如果我使用:
WindowManager windowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Log.d("askj", width + "+" + height);
或我得到的其他相关方法:
1440+2560
我正在使用这些参数来设置背景,如果我使用第二种方法,我可以清楚地看到整个屏幕尺寸没有被占用。我真的不想使用Runnable() 那么有什么办法可以解决这个问题吗?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/background"
tools:context="com.example.home.background.HomeScreen">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/img"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textStyle="bold"
android:layout_centerInParent="true"
android:textSize="22sp"
/>
</RelativeLayout>
【问题讨论】:
-
向我们展示定义ID为
R.id.background的RelativeLayout的布局文件。 -
我刚刚更新了布局
-
如果它是你想要的,为什么不直接使用 DisplayMetrics 呢?
-
如果我使用显示指标,即使我在实际绘制背景颜色时得到这些值,它也只显示在屏幕的 90% 上(宽度,高度都可以)
-
等等,
match_parent应该总是有效的。我以为你对实际值感兴趣。