【问题标题】:Why am I getting java.lang.ClassCastException on checkbox.getTag()?为什么我在 checkbox.getTag() 上得到 java.lang.ClassCastException?
【发布时间】:2018-01-17 23:59:53
【问题描述】:

你能告诉我为什么我的代码不起作用吗?它曾经运行良好,现在我从 listView 切换到 recyclerView 我得到了:

java.lang.ClassCastException: java.lang.Integer cannot be cast to com.app.SelectPhoneContact

无论哪个复选框在我的recyclerView 中,它应该是toast 对应的那些被选中的数字。

 Button btnGetItem = (Button) findViewById(R.id.btnGetItem);
        btnGetItem.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //loop through the Matching Contacts
                int count = MatchingContactsAsArrayList.size();

                for (int i = 0; i < count; i++) {
                    //for each Matching Contacts row in the recyclerview
                    LinearLayout itemLayout = (LinearLayout) recyclerView.getChildAt(i); // Find by under LinearLayout
                    //for each Matching Contacts checkbox
                    CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);
                    //get other data related to the selected contact - name and number
                    SelectPhoneContact data = (SelectPhoneContact) checkbox.getTag();

                    //if that checkbox is checked, then get the phone number
                    if (checkbox.isChecked()) {

                        Toast.makeText(NewContact.this, data.getPhone(), Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

错误在303行,即:

SelectPhoneContact data = (SelectPhoneContact) checkbox.getTag();

【问题讨论】:

  • 您在哪里以及如何设置标签?
  • 在我的recyclerViewAdapter 上的onBindViewHolder 中有CheckBox check = ((MatchingContact) viewHolder).check; check.setTag(position);,这是我需要的。是否只是在那里设置另一个标签,如 check.setTag(data);

标签: java android android-recyclerview


【解决方案1】:

如果您想要两个标签,请使用the two-parameter setTag()the one-parameter getTag()

或者,使用您正在使用的方法创建一个保存数据的对象(视图持有者模式)并将其与标签相关联。

【讨论】:

    【解决方案2】:

    您似乎将Integer 类型对象设置为复选框的标记对象,并尝试将其转换为OnClickListener 中的SelectPhoneContact 对象。

    【讨论】:

      【解决方案3】:

      checkbox.getTag()Integer 格式返回数据,而您正试图将其转换为SelectPhoneContact,这就是您得到ClassCastException 的原因,因为您试图将对象转换为它不是实例的子类.

      【讨论】:

        猜你喜欢
        • 2019-11-07
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 2014-01-29
        相关资源
        最近更新 更多