当前位置: 首页 > 知识库问答 >
问题:

IllegalStateException:创建Viewholder视图时不能附加。确保没有将'true'传递给attachToRoot参数

鲍向笛
2023-03-14

片段类

open class BaseScanItemFragment : BaseSOFFragment(), OnItemClickListener {

    private lateinit var binding: FragmentScanItemBinding
    lateinit var viewModel: ScanItemViewModel
    val progressBar = CustomProgressBar()
    var adapterSize = 0
    var selectedPos = 0
    var scanItemModel: List<ScanItemModel>? = null

    override fun getCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_scan_item,
            container,
            false
        )
        //Progress Bar with Text
        progressBar.show(activity as MainActivity, "Please Wait...")
        viewModel = ViewModelProviders.of(this).get(ScanItemViewModel::class.java)

        viewModel.departmentsList.observe(this, Observer {
            updateDepartmentSpinner()
        })

        getScannedItemDetails("")

        activity?.let {
            binding.upcScanText.setOnEditorActionListener { v, keyCode, event ->
                if (keyCode == EditorInfo.IME_ACTION_DONE) {

                    var upcRetailText = upcScanText.text.toString()
                    upcScanText.text.clear()
                    getScannedItemDetails(upcRetailText)
                }
                false
            }
        }

        binding.lifecycleOwner = viewLifecycleOwner
        binding.scanItemViewModel = viewModel
        binding.scanItemInterface = this
        setupListPeopleView(binding.recyclerView.scanItems)
        val content = SpannableString("r667yyy")
        content.setSpan(UnderlineSpan(), 0, content.length, 0)
        binding.textViewItemName.setText(content)

        viewModel.getTotalCount().observe(this, Observer {
            val df = DecimalFormat("#.##")
            df.roundingMode = RoundingMode.CEILING
            totalCost.text = "$" + df.format(it.toFloat()).toString()
        })

        return binding.root
    }

    private fun setupListPeopleView(scanItemRecycleView: RecyclerView) {
        val adapter = ScanItemAdapter()
        scanItemRecycleView.adapter = adapter
        scanItemRecycleView.layoutManager = LinearLayoutManager(context)
        adapter.setListener(this)
    }

    private fun getScannedItemDetails(upsText: String) {
        viewModel.getItems(upsText).observe(this, Observer {
            viewModel.setScannedData()
            updateUI()
            val scanItemAdapter = binding.recyclerView.scanItems.adapter as ScanItemAdapter
            scanItemAdapter.setScanItemList(it)
            adapterSize = it.size
            scanItemModel = it
        })
    }

    private fun updateDepartmentSpinner() {

        var listDepartment: List<DepartmentsModel>? = null
        progressBar.dialog.dismiss()
        activity?.let { it ->
            viewModel.departmentsList.observe(this, Observer {
                listDepartment = it
            })
        }
        val departmentAdapter: ArrayAdapter<String>? =
            activity?.let {
                ArrayAdapter<String>(
                    it,
                    android.R.layout.simple_spinner_item,
                    viewModel.updateStringList()
                )
            }
        deptSpinner.setAdapter(departmentAdapter)
        deptSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {

            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                scanItemModel?.get(selectedPos)?.deptName = listDepartment!![position].deptName
                scanItemModel?.get(selectedPos)?.deptID = listDepartment!![position].deptID
            }
        }
    }

    private fun updateUI() {
        upcText.setText(viewModel.retailUPs)
        val content = SpannableString(viewModel.descriptionLink)
        content.setSpan(UnderlineSpan(), 0, content.length, 0)
        linkDesc.text = content
        unitCost.setText("$" + viewModel.unitCost)
        extCost.setText("$" + viewModel.extCost)
        overrideExtCost.setText("$" + viewModel.overrideCost)
        totalCost.text = "$" + viewModel.overrideCost
        PrefUtil(requireContext()).save("UnitCost", viewModel.unitCost)
        PrefUtil(requireContext()).save("OverrideExtCost", viewModel.overrideCost)
        PrefUtil(requireContext()).save("TotalCost", viewModel.overrideCost)

        val uomCategories: MutableList<String> = ArrayList()
        uomCategories.add("KG")

        val uomAdapter: ArrayAdapter<String>? =
            activity?.let {
                ArrayAdapter<String>(
                    it,
                    android.R.layout.simple_spinner_item,
                    uomCategories
                )
            }
        unitSpinner.setAdapter(uomAdapter)

    }

    override fun getViewCreated(view: View, savedInstanceState: Bundle?) {
        Log.v("Test", "Test")
    }

    override fun getTitle(): String {
        return resources.getString(R.string.scan_items)
    }

    override fun getToolBarIcon(): IntArray {
        return intArrayOf(Utils.ICON_VISIBLE, Utils.ICON_VISIBLE)
    }

    override fun getToolBarLogoImage(): Int {
        return 0
    }

    override fun isToolbarVisible(): Boolean {
        return true
    }

    override fun onClick(v: View?) {
    }

    override val kodein: Kodein
        get() = TODO("Not yet implemented")


    override fun onItemClick(position: Int) {
        Toast.makeText(activity, "Clicked Item --> " + position, Toast.LENGTH_SHORT).show()
        selectedPos = position
    }

    override fun onCountChanged(listScanModel: List<ScanItemModel>) {
        viewModel.setTotalCount(listScanModel)
    }

class ScanItemAdapter() : RecyclerView.Adapter<ScanItemAdapter.DateViewHolder>(){

    private var scanItemList: List<ScanItemModel>? = null
    private lateinit var scanItemViewModel: ItemScanListBinding
    private lateinit var listener: OnItemClickListener

    init {
        this.scanItemList = emptyList()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DateViewHolder {
        Log.v("Clicked_ADAPTER", "Clicked itemLookup 28")
        scanItemViewModel = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_scan_list,
                parent, false)
        Log.v("Clicked_ADAPTER", "Clicked itemLookup 31")
        return DateViewHolder(scanItemViewModel)
    }

    override fun onBindViewHolder(holder: DateViewHolder, position: Int) {
        Log.v("Clicked_ADAPTER", "Clicked itemLookup 36")
        holder.bindScanItemDetail(scanItemList!![position])
    }

    override fun getItemCount(): Int {
        return scanItemList!!.size
    }

    fun setScanItemList(scanList: List<ScanItemModel>) {
        this.scanItemList = scanList
        notifyDataSetChanged()
    }

    fun setListener(listener: OnItemClickListener) {
        this.listener = listener
    }

    inner class DateViewHolder(private var itemDetailBinding: ItemScanListBinding) : RecyclerView.ViewHolder(itemDetailBinding.scanDetail) {

        fun bindScanItemDetail(scanItemResponse: ScanItemModel) {
            if (itemDetailBinding.scanItemDetailModel == null) {
                itemDetailBinding.scanItemDetailModel =
                    ScanItemDetailViewModel(scanItemResponse, itemView.context)
            } else {
                itemDetailBinding.scanItemDetailModel!!.setScanDetail(scanItemResponse)
                itemDetailBinding.executePendingBindings()
            }

            itemDetailBinding.root.setOnClickListener {
                Log.v("Click", "Click")
                listener.onItemClick(layoutPosition)
            }

            itemDetailBinding.root.quantityValue.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(p0: Editable?) {
                    Log.v("Click", "AfterText")
                }

                override fun beforeTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                    Log.v("Click", "BeforeText")
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                    Log.v("Click", "onText")
                    if(s.isNotEmpty()) {
                        scanItemList!!.get(layoutPosition).count = s.toString().toInt()
                        scanItemList!!.get(layoutPosition).pack = s.toString()
                        listener.onCountChanged(scanItemList!!)
                    }
                }
            }
            )

            itemDetailBinding.root.itemLookup.setOnClickListener {
                Log.v("Clicked_ADAPTER", "Clicked itemLookup")
            }

            itemDetailBinding.root.itemDelete.setOnClickListener {
                Log.v("Clicked_ADAPTER", "Clicked itemDelete")
            }

        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="scanItemDetailModel"
            type="com.sample.viewModel.common.ScanItemDetailViewModel" />
    </data>

    <com.sample.utilities.SwipeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:dragFromEdge="right">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="30dp">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_vertical|end"
                android:paddingStart="20dp"
                android:paddingEnd="20dp"
                android:orientation="horizontal">

                <ImageButton
                    android:id="@+id/itemLookup"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="#2d8dfd"
                    app:srcCompat="@drawable/ic_search_24dp"
                    android:text="Item Lookup"/>

                <ImageButton
                    android:id="@+id/itemDelete"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:background="#ff0000"
                    app:srcCompat="@drawable/ic_delete_24dp"
                    android:text="Delete"/>

            </LinearLayout>
        </FrameLayout>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/scanDetail"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp">

            <TextView
                android:id="@+id/itemDescription"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:layout_marginTop="1dp"
                android:layout_marginEnd="60dp"
                android:ellipsize="end"
                android:hint="@string/app_name"
                android:maxLines="1"
                android:text="@{scanItemDetailModel.description}"
                android:textAlignment="center"
                android:textColor="@color/colorBlack"
                app:layout_constraintRight_toLeftOf="@+id/quantityValue"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <EditText
                android:id="@+id/quantityValue"
                android:layout_width="40dp"
                android:layout_height="25dp"
                android:layout_marginRight="3dp"
                android:background="@drawable/edit_text_shape"
                android:maxLines="1"
                android:paddingLeft="5dp"
                android:paddingTop="3dp"
                android:paddingRight="7dp"
                android:paddingBottom="3dp"
                android:text="@{scanItemDetailModel.quantity}"
                android:textAlignment="textEnd"
                android:textSize="16sp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </com.sample.utilities.SwipeLayout>
</layout>

如何调试

共有1个答案

慕乐语
2023-03-14
 RecyclerView.ViewHolder(itemDetailBinding.scanDetail)

这里将子布局scandetail传递给父构造函数。你不应该那样做;传递的视图不应附加到任何父级。

改为传递ItemDetailBinding.root

 类似资料:
  • 在这个问题上我需要一些帮助。幸好我得到了这个错误。我没有做任何修改,也找不到解决方案...这里有一个错误。 IllegalStateException:创建ViewHolder视图时不能附加。确保您没有将'true'传递给位于Android.support.v7.widget.recyterView$adapter.createViewWholder(recycerview.java:6687)和

  • 启用minifyEnabled后,在我的gradle文件中启用ḿy应用程序继续崩溃。我已经搜索了很多,但我觉得与Proguard不太适应,我也不确定问题出在哪里。也许我需要添加更多的keep in proguard rules pro? build.gradle 前进的规则。赞成的意见 错误: 有什么想法吗?提前谢谢。

  • 问题内容: 在我的RCP应用程序中,左侧有一个用于导航的视图,右侧有一个用于视图的文件夹。透视图看起来像这样: 我想根据用户在导航树中选择的内容打开不同的视图。认为这并不难。我的导航树视图: 这似乎很好。仅有一个小问题:我需要以某种方式将对象(例如,selectedItem)传递给我的视图,以使用户与其内容进行交互。我怎么做? 我看到了一些示例,其中一些同事编写了自己的视图,并将其放置在右侧。然后

  • 问题内容: 我需要在Node.JS应用程序中观察少量目录: 问题在于fs.watch仅将文件名传递给回调函数,而没有包括它所在的目录。我是否可以通过某种方式将额外的参数传递给updated()函数,以便它知道文件在哪里? 我认为我正在寻找类似于Python的工具,如果有帮助的话。 问题答案: 您可以使用:

  • 问题内容: 我有一个使用处理程序发布可运行实例的线程。它工作得很好,但是我很好奇我如何将参数传递给Runnable实例使用?也许我只是不了解此功能的工作原理。 为了避免出现“您为什么需要此问题”的问题,我有一个线程化的动画,必须调出UI线程来告诉它实际绘制的内容。 问题答案: 只需使用接受参数的构造函数实现的类就可以了, 您可以使用参数化构造函数创建Runnable类的实例。

  • 问题内容: 我正在使用$ .ajax将数据发布到服务器。但是,我想向“成功”回调传递一个附加参数,以告知回调函数响应所针对的HTML元素的ID。 有可能的?喜欢: 问题答案: 通过在与局部变量相同的作用域中声明函数文字,该函数将成为可以访问该局部变量的 闭包 。(或者有人会说,只有当函数文字也引用了未在其范围内定义的非全局变量时,它才成为 闭包 。