我需要通过扩展LinearLayout来获取我正在创建的自定义视图的宽度。我最初的尝试是做
int width = this.getLayoutParams().width
但是,这只会返回-1。
接下来,我尝试覆盖onMeasure(int, int)
@Override
protected void onMeasure(int width, int height) {
super.onMeasure(width, height);
this.width = MeasureSpec.getSize(width);
}
这样可以获得宽度,但是在实际需要宽度之后它才被执行(我猜视图还没有建成?)
我特别需要使用此方法的Google地图:`map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, MAP_PADDING));
有关获得宽度的任何建议吗?
答案 0 :(得分:0)
除非您明确将视图的宽度/高度设置为静态值(如x-dp或match_parent),否则在onMeasure循环完成之前,您无法知道视图的大小。 Android也可以多次调用onMeasure来找到合适的大小,因此它不是找到确切大小的最佳位置。您可能必须找到一种方法来将map.moveCamera延迟到onLayout函数。
答案 1 :(得分:0)
您可以按照以下方式执行此操作:
// Name the activity's root view - your custom linear layout
View view = findViewById(R.id.customLinearLayout)
int width = view.getRootView().getWidth(); // this returns the actual width of the view
这一直对我有用