android - android中的线性布局( View )大小

标签 android view width android-linearlayout

在我的应用程序中,我在 linearlayout 中有 gridview。由于屏幕尺寸不同,我想计算 gridview 容器的宽度(在线性布局中),然后我将决定屏幕上应显示多少列。我的问题是。当我写

linearlayout.getwidth();

它返回 0,这是因为在 oncreate 方法中获取 View 大小还为时过早。

获取 View 高度或宽度的干净解决方案是什么。

我试过了

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int gridSize = display.getWidth();

但 android 表示它已弃用 :(

最佳答案

Display.getWidth()Display.getHeight() 都从 API 13 开始弃用,取而代之的是 Display.getSize(Point) .为了与两者兼容,您必须进行版本检查并选择合适的。

我是这样做的:

Point size = new Point();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
if (Build.VERSION.SDK_INT >= 13) {
    display.getSize(size); // API 13+
} else {
    size.x = display.getWidth();
    size.y = display.getHeight();
}

然后,size.x 就是您的宽度。 (不要忘记在方法签名之前加上 @TargetApi(13) @SuppressWarnings("deprecation")。)

请记住,这是单位的显示宽度;如果你想简单地获取一个 View 的大小,你必须在 UI 布局后调用它。这与这个答案略有无关,但您可以在 this thread's answer 中找到解决方案。相反。

关于android - android中的线性布局( View )大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14468547/

相关文章:

Android - 在自定义适配器中设置文本时出现 NPE

android - Android Studio:在我的项目中进行更改后,是否需要在生成签名的apk之前手动进行项目?

ios - 仅为特定 View 禁用手势识别器

ruby-on-rails - rails 3.1 : How can I stop the view from displaying the array along with the data for 2 associated models?

html - 菜单列表项宽度拒绝更改?

c# - Windows Mobile 应用程序中 DataGrid 的列宽

file - 有没有办法设置 <input type ='file'/> 的宽度以在 Firefox 中显示?

java - Listview android 值在滚动中混淆

android - Roboguice/getInstance + 最佳实践

java - 我如何知道 View 是否已绘制