我试图确定屏幕的宽度和高度,以便在片段中使用它们。
我的片段布局的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>
答案 0 :(得分:0)
您可以使用measure
方法在活动将其添加到视图层次结构之前测量背景视图。
background = (RelativeLayout) view.findViewById(R.id.background);
background.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
int backgroundHeight = background.getMeasuredHeight();
int backgroundWidth = background.getMeasuredWidth();
在我的情况下,我测量了一个膨胀的视图,但它的宽度和高度设置为match_paent
。
View view = inflater.inflate(R.layout.table_field_text, null, false);
view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int viewHeight = view.getMeasuredHeight();
答案 1 :(得分:0)
使用ViewTreeObserver,如下所示:
AuthService