当布局再次膨胀时,视图为null

时间:2018-08-08 11:45:55

标签: android kotlin kotlin-android-extensions

我有一个包含4个容器(LinearLayouts)的视图。每个容器将根据数据填充内容。 (每个内容视图都以一种布局夸大并添加到容器中)

以前,我在加载数据时对每个布局进行了夸大之后调用了ButterKnife.bind(this, view)。现在,我想摆脱ButterKnife,转而使用kotlinx合成视图绑定。

我的问题是,第一次创建视图并进行设置时一切正常。当我刷新视图时,大多数视图为空(以前不为空,也不应该为空)。

某些代码:

private fun refresh() {
    //Get data...then...
    //Reset containers
    topup_container_one.removeAllViews()
    topup_container_two.removeAllViews()
    topup_container_three.removeAllViews()
    topup_container_four.removeAllViews()

    lateinit var contentOne: View
    lateinit var contentTwo: View
    lateinit var contentThree: View
    lateinit var contentFour: View
    val layoutInflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    if (someCondition) {
        contentOne = layoutInflater.inflate(R.layout.layout1, topup_container_one, false)
        contentTwo = layoutInflater.inflate(R.layout.layout2, topup_container_two, false)
        contentThree = layoutInflater.inflate(R.layout.layout3, topup_container_three, false)
        contentFour = layoutInflater.inflate(R.layout.layout4, topup_container_four, false)       
    } else { 
         // some other sort order, same principle
    }

    topup_container_one.addView(contentOne)
    topup_container_two.addView(contentTwo)
    topup_container_three.addView(contentThree)
    topup_container_four.addView(contentFour)
} 

布局:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:orientation="vertical">
<LinearLayout
    android:id="@+id/topup_container_one"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    </LinearLayout>

   //same for two, three, four

</LinearLayout>

关于该视图混乱,我有什么可以做的吗?也许会“召回”视图绑定?

1 个答案:

答案 0 :(得分:0)

在为每个容器充气后再次手动绑定视图时,它会起作用。

所以,我要做什么:

private var buttonVoucherVoiceInput: AppCompatImageButton? = null
private var editTextVoucher: EditText? = null
private var textInputLayoutVoucher: TextInputLayout? = null
private var buttonVoucherSubmit: Button? = null
//And many many more

private fun refresh() {

    ///...
    topup_container_one.addView(contentOne)
    topup_container_two.addView(contentTwo)
    topup_container_three.addView(contentThree)
    topup_container_four.addView(contentFour)

    //Find views again
    editTextVoucher = view!!.findViewById(R.id.topup_edittext_voucher)
    buttonVoucherSubmit = view!!.findViewById(R.id.topup_button_voucher_submit)
    textInputLayoutVoucher = view!!.findViewById(R.id.topup_til_voucher)
    buttonVoucherVoiceInput = view!!.findViewById(R.id.topup_button_voucher_voice)

}

烦人,但又可以正常工作。我可以从项目中删除Butterknife。 (不要无礼,我喜欢):)

相关问题