我正在寻找一种技术来确定 Java 中 Android Wear 设备屏幕是圆形还是矩形。请注意,这不仅仅涉及布局;还涉及布局。我的代码实际上需要知道它正在使用哪种形状,因为它们的处理方式不同。
据我从在线代码示例中看到,两种不同的方法应该是可能的 - 但我一直无法让它们中的任何一个工作。我将它们放在这里是为了将它们从运行中消除,或者进行可能的故障排除(如果有人可以看到它们的问题)。请不要让我参考另一篇仅重申此处对我不起作用的解决方案的帖子。
请注意,此处的所有代码都在手表上运行。另外,我仍在使用 Eclipse,FWIW。
我见过的最简单的方法是添加一个onApplyWindowInsets()
侦听我的布局中的视图。所以我创建了一个如下所示的侦听器:
@Override
public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
if (insets.isRound()) {
displayShape = "round";
} else {
displayShape = "rectangular";
}
return null;
}
并将其添加到我的布局的根视图中,代码如下:
view.setOnApplyWindowInsetsListener(this);
在我的 onCreate() 方法中。就目前而言看起来还不错——但是监听者永远不会被调用。我还发现建议说我需要手动调用它,如下所示:
view.requestApplyInsets();
但这似乎没有任何区别。我尝试过将其放在不同的视图、不同的生命周期方法等中,但从未见过它在我的应用程序中实际被调用。顺便说一句,这是在我的 LG G Watch 上运行的。
第二种方法是一种黑客方法,基于已发布的WatchViewStub
助手类。我费尽心思将可穿戴支持库导入到 Eclipse 项目中,然后将以下内容添加到我的根布局中:
<android.support.wearable.view.WatchViewStub
android:id="@+id/watch_view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rectLayout="@layout/rect"
app:roundLayout="@layout/round"
/>
并创造了rect.xml
像这样:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_type"
android:text="rectangular"
/>
and round.xml
像这样:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/layout_type"
android:text="round"
/>
最后,在我的onCreate()
我添加了以下 Java 代码:
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
TextView layoutType = (TextView) findViewById(R.id.layout_type);
displayShape = layoutType.getText().toString();
}
});
虽然距离街区很远,但应该可以用,对吗?没那么多...displayShape
始终设置为"rectangular"
,表明它总是rect.xml
即使在圆形模拟器上运行,也会被使用。 [我还没有圆屏硬件来尝试。]
那么有人看出我这两种方法哪里出了问题吗?或者你能建议第三种实际有效的方法吗?