我正在尝试确定屏幕的宽度和高度,以便在片段中使用它们。我的片段的布局具有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>发布于 2016-02-12 18:14:33
在activity将背景视图添加到视图层次结构之前,您可以使用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();发布于 2016-02-12 21:33:40
使用ViewTreeObserver,如下所示:
background = (RelativeLayout) view.findViewById(R.id.background);
final ViewTreeObserver vto = background.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
//get View Width and height here
int width = background.getWidth();
int height = background.getHeight();
//Call anyfunction which uses width and height here
function(width,height);
//Then remove layoutChange Listener
ViewTreeObserver vto = background.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
vto.removeOnGlobalLayoutListener(this);
} else {
vto.removeGlobalOnLayoutListener(this);
}
}
}); https://stackoverflow.com/questions/35351028
复制相似问题