WatchViewStub 的宽度和高度

Width & height of a WatchViewStub

我正在手表 activity 上使用 WatchViewStub,磨损 android (API 23)。

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

不幸的是,我的存根视图 getWidth()getHeight() 总是 return 0,即使我通过使用 setOnLayoutInflatedListener.

如何获取 a 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
    }
  });
}

试试这个:

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