查找片段内部视图的宽度

我想find一个片段的视图的宽度,我已经写了下面的代码

class ExampleFragment : Fragment() { var team1_value = 0 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val v = inflater!!.inflate(R.layout.fragment_queens, container, false) val width = v.layout_team1_picker.width.toFloat() Log.d("width1","width is $width") return v } 

我得到的答案是0.0。 如果我在按钮里面做同样的事情

 class ExampleFragment : Fragment() { var team1_value = 0 override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val v = inflater!!.inflate(R.layout.fragment_queens, container, false) v.image_team1_plus.setOnClickListener{ val width = v.layout_team1_picker.width.toFloat() Log.d("width2","width is $width") } return v } 

每当我按下按钮,我得到一个积极的320.0。 这是为什么?

因为在onClick的情况下,当按钮被点击时(即在视图被打包/呈现之后),你正在运行代码。 在onCreateView的情况下,你在运行代码的时候是在它被打包/渲染之前运行的,所以它还没有大小。

如果将显示宽度的代码从onCreateViewonStart (在片段可见时调用),则应该看到所需的行为。

重写onViewCreated方法并获取里面的宽度。

正如其他答案中所述,在onCreateView期间,您的视图仍然没有大小。 另一种方法是添加一个GlobalLayoutListener,以了解您的视图何时被渲染。

有不同的方式来实现这一点,这是一个很好的细分: https : //antonioleiva.com/kotlin-ongloballayoutlistener/

基本上:

创建一个扩展函数为1.等待视图被渲染(通过将globalLayoutListener附加到它的viewTreeObserver)2.一旦知道宽度/高度,调用你想要的任何函数

 inline fun  T.afterMeasured(crossinline f: T.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) } 

要打电话,只需做:

 v.layout_team1_picker.afterMeasured { Log.d("width1","width is $v.layout_team1_picker.width") }