android - 检查元素是否适合屏幕

标签 android ios titanium

我在我的应用中添加了一个 View ,定义如下:

Ti.UI.createView({
    top: 0,
    left: 0,
    width: '50%'
    height: '460dp',
    backgroundColor: 'red'
});

我想知道上面的 View 是否适合屏幕。 IE。用户的屏幕是否足够高以完全显示我的整个 View 。我尝试了以下方法:

function getPixels(dp) {
    return (dp + (Ti.Platform.displayCaps.dpi / 160));
}

alert(460); // 920
alert(Ti.Platform.displayCaps.platformHeight); // 1136

这在 iphone 模拟器上似乎是正确的。然而,当我在我的安卓设备上运行完全相同的代码时,我得到了结果:

屏幕高度:1200
View 高度:690

这似乎不正确,因为红色背景的 View 在 iphone 模拟器上占用的空间几乎与在我的 android 设备上占用的空间一样多。

有什么方法可以在所有设备(ios 和 android)上获得一致的结果。或者有其他方法可以解决我的问题吗?

最佳答案

如果您尝试支持所有尺寸,为什么不将高度也设置为 % 值?

在回答您的问题时,您需要考虑的主要事情是Ti.Platform.displayCaps.platformHeight 以特定于平台的单位返回值;所以Android上的像素和iOS上的密度无关像素(dip)。由于您使用与密度无关的像素设置 View 高度,因此您希望将这些平台单位转换为与密度无关和与平台无关的单位。

我通常只使用 measurement library provided由钛合金制成。

var measurement = require('alloy/measurement');
var dpHeight = measurement.pxToDP(Ti.Platform.displayCaps.platformHeight);
if(460 < dpHeight) {
    alert('Fits');
} else {
    alert("does not fit');
}

但实际上我发现仅使用具有百分比值的相对布局要容易得多。

另一种确定 View 是否在边界内(事后)的方法是添加一个 postlayout event listener,当这个事件被触发时,它意味着布局边界已经以系统单位计算并且现在可以访问:

view.addEventListener('postlayout', function(e) {
    if(view.rect.height + view.rect.y > Ti.Platform.displayCaps.platformHeight) {
        alert('Does not fit")
    }
});

关于android - 检查元素是否适合屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20125692/

相关文章:

android - 将 Phonegap 的各个部分混合到 native 应用程序中

ios - 使用钛创建 XML 文档

java - Android View 类似于 Google 的 Youtube 应用程序?

java - 如何通过变量填充进度条?

ios - 将自动释放对象分配给保留属性是否会增加其保留计数?

ios - 以编程方式使用 UINavigationController 设置 RootViewController

eclipse - Titanium Studio错误: when I run the the default mobile project with Android emulator

android - 选择文件对话框

android - 如何有效地在 gridview 中加载互联网图像?

ios - 如何使用 PHPicker 从图库中获取 WebP 图片