宽度和宽度WatchViewStub的高度

时间:2016-06-23 07:11:06

标签: android wear-os

我在使用android wear(API 23)的观看活动中使用WatchViewStub

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

不幸的是,我的存根视图getWidth()getHeight()总是返回0,即使我等待通过设置setOnLayoutInflatedListener的侦听器来扩充布局。< / p>

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

1 个答案:

答案 0 :(得分:0)

请改为尝试:

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