找到片段内部视图的宽度

时间:2018-01-22 23:30:38

标签: android-fragments kotlin

我想在片段内找到视图的宽度,并且我已经编写了以下代码

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。为什么会这样?

3 个答案:

答案 0 :(得分:0)

因为在onClick情况下,您在单击按钮时运行代码,即在打包/渲染视图之后。在onCreateView的情况下,您在创建代码时会运行代码,这是在打包/渲染之前,因此它还没有大小。

如果您将宽度显示代码从onCreateView移动到onStart(在片段可见时调用),那么您应该会看到所需的行为。

答案 1 :(得分:0)

覆盖onViewCreated方法并获取内部宽度。

答案 2 :(得分:0)

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

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

基本上:

创建扩展功能  1.等待视图呈现(通过将globalLayoutListener附加到其viewTreeObserver)  2.一旦知道宽度/高度,就调用你想要的任何功能

inline fun <T: View> 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")

}