【问题标题】:Width & height of a WatchViewStubWatchViewStub 的宽度和高度
【发布时间】:2016-06-28 05:57:46
【问题描述】:

我在带有 android wear (API 23) 的手表活动中使用WatchViewStub

我正在尝试获取活动视图的宽度和高度,因为我想根据相对于视图中心的触摸事件进行一些计算。

不幸的是,我的存根视图的getWidth()getHeight() 总是返回0,即使我通过使用setOnLayoutInflatedListener 设置侦听器来等待布局膨胀。

如何获取WatchViewStub 的实际大小?

以下是相关代码:

protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

 WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
 Log.d(TAG, stub.getWidth()); // -> 0
 Log.d(TAG, stub.getHeight()); // -> 0

 stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
    @Override
    public void onLayoutInflated(WatchViewStub stub) {
       Log.d(TAG, stub.getWidth()); // -> 0
       Log.d(TAG, stub.getHeight()); // -> 0
    }
  });
}

【问题讨论】:

  • 您可能过早地调用函数。尝试覆盖onMeasure
  • @jitinsharma 谢谢。但是,我更喜欢不需要覆盖视图的解决方案。

标签: android wear-os


【解决方案1】:

试试这个:

stub.getViewTreeObserver()
        .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                stub.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                Log.d(TAG, "dimens = " + stub.getWidth() + " x " + stub.getHeight());
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多