我之前在评论中的意思是,这里有许多流行的解决方案来获取任何 android 视图的高度和宽度。
我现在已经测试了这段代码,它工作正常。试试这个:
final RelativeLayout topLayout = (RelativeLayout) findViewById(R.id.topRelLayout);
ViewTreeObserver viewTreeObserver = topLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 16)
topLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
topLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int viewWidth = tabs.getWidth();
int viewHeight = tabs.getHeight();
Toast.makeText(HomeScreenActivity.this, "height = " + viewHeight + " width = " + viewWidth , 2000).show();
}
});
}
topRelLayout 是 xml 文件的根布局的 id,tabs 是对标签视图的引用。
即使遵循简单的代码也可以正常工作。
tabs.post(new Runnable() {
@Override
public void run() {
int w = tabs.getMeasuredWidth();
int h = tabs.getMeasuredHeight();
Toast.makeText(HomeScreenActivity.this, "height = " + h + " width = " + w , 2000).show();
}
});
使用任何一种解决方案,您都可以获得任何屏幕尺寸的任何视图的高度/宽度。
编辑:
阅读您编辑的问题后,我假设您需要 Tab 小部件占用了多少屏幕百分比。
我知道可以实施的唯一解决方案是:
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final Display display = wm.getDefaultDisplay();
tabs.post(new Runnable() {
@Override
public void run() {
int h = tabs.getMeasuredHeight();
int screenHeight = 0;
if(Integer.valueOf(android.os.Build.VERSION.SDK_INT) >= 13)
{
Point point = new Point();
display.getSize(point);
screenHeight = point.y;
}
else
screenHeight = display.getHeight();
double tabPart = (((double)h/(double)screenHeight) * 100);
Toast.makeText(HomeScreenActivity.this, "height = " + screenHeight + " tabPart = " + tabPart + " %", 2000).show();
}
});