【问题标题】:ArrayindexOutOfBounds Exception strange tried to refactor many times Kotlin issue [closed]ArrayindexOutOfBounds Exception 奇怪的尝试多次重构 Kotlin 问题 [关闭]
【发布时间】:2019-05-27 13:29:52
【问题描述】:

该应用有两个选项卡的底部导航,一个用于任务,一个用于笔记。

我一开始没有错误,因为它是通过加载任务开始的。但是当我按下笔记标签时它崩溃了。

从主列表的位置减去 1,因为我在顶部(数组中的第一个位置)添加了一个按钮,认为这会更正它。

BaseRecyclerAdapter 类

abstract class BaseRecyclerAdapter<T>(
    protected val masterList: MutableList<T> = mutableListOf()
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    override fun getItemCount(): Int = masterList.size + 1

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is TaskAdapter.AddButtonViewHolder) {
            holder.onBind(Unit)
        } else {
            (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
        }
    }


    override fun getItemViewType(position: Int): Int =
        if (position == 0) {
            TYPE_ADD_BUTTON
        } else {
            TYPE_INFO
        }

    abstract class BaseViewHolder<E>(val view: View) : RecyclerView.ViewHolder(view) {
        abstract fun onBind(data: E)
    }

    abstract class AddButtonViewHolder(view: View) : BaseViewHolder<Unit>(view)

    companion object {
        const val TYPE_ADD_BUTTON = 0
        const val TYPE_INFO = 1
    }
}

NotesAdapter

class NoteAdapter(notesList: MutableList<Note> = mutableListOf()) : BaseRecyclerAdapter<Note>(notesList) {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if(viewType == TYPE_ADD_BUTTON){
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        } else {
            NoteViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false))

        }

    override fun getItemViewType(position: Int): Int =
        if(position == 0){
            TYPE_ADD_BUTTON
        }else {
            TYPE_INFO
        }


    override fun getItemCount(): Int = masterList.size + 1


    class NoteViewHolder(view: View) :BaseViewHolder<Note>(view){

        override fun onBind(data: Note) {
            (view as NoteView).initView(data)
        }
    }

    class AddButtonViewHolder(view: View): BaseRecyclerAdapter.AddButtonViewHolder(view){
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_note)
        }

    }
}

笔记列表片段

class NotesListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_notes_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerViewNote.layoutManager = LinearLayoutManager(context)
        val adapter = NoteAdapter(mutableListOf(
            Note("Ben Mohammad", null),
            Note("Joesph and and Maria", null)
        ))
        recyclerViewNote.adapter = adapter
    }

    companion object {

        fun newInstance() = NotesListFragment()
    }

}

笔记视图

class NoteView @JvmOverloads constructor (context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr){

    fun initView(note: Note){
        description.text = note.description
  }
}

我使用了嵌套的自定义视图这就是我想要做的......显然试图让它非常 OOP 风格被它卡住......

class TaskAdapter(
    tasksList: MutableList<Task> = mutableListOf()
) : BaseRecyclerAdapter<Task>(tasksList) {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if (viewType == TYPE_INFO) {
            TaskViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false))
        } else {
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        }

    class TaskViewHolder(view: View) : BaseViewHolder<Task>(view) {

        override fun onBind(data: Task) {
            (view as TaskView).initView(data)

        }
    }


    class AddButtonViewHolder(view: View) : BaseRecyclerAdapter.AddButtonViewHolder(view) {
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_task)
        }

    }


}

任务列表片段

class TasksListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tasks_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = TaskAdapter(
            mutableListOf(
                Task(
                    "Testing one!!",
                    mutableListOf(
                        Todo("Test 1!!"),
                        Todo("Test 2!!", true)


                    )
                ),
                Task("Testing two!!")
            )
        )
        recyclerView.adapter = adapter
    }

    companion object {


        fun newInstance() = TasksListFragment()
    }

}

任务视图

class TaskView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr) {


    lateinit var task: Task

    fun initView(task: Task) {
        this.task = task

        titleView.text = task.title
        task.todos.forEach {

                todo ->
            val todoView =
                (LayoutInflater.from(context).inflate(R.layout.view_todo, todoContainer, false) as TodoView).apply {
                    initView(todo) {
                        if (isTaskcomplete()) {
                            createstrikeThrough()
                        } else {
                            removeStrikeThrough()
                        }

                    }
                }


            todoContainer.addView(todoView)

        }
    }

    fun isTaskcomplete(): Boolean = task.todos.filter { !it.isComplete }.isEmpty()

    private fun createstrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        }


    }

    private fun removeStrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
        }

    }
}

更多课程,all code is pushed to GitHub。

【问题讨论】:

标签: android android-studio kotlin


【解决方案1】:

问题出在这里:

if (holder is TaskAdapter.AddButtonViewHolder) { // <--- problematic line
    holder.onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}

BaseRecyclerAdapter 有两个不同的子类:TaskAdapter 和 NotesAdapter。当为您的NotesAdapter 调用位置0 时,if (holder is ...) 检查将失败,因为类型为NotesAdapter.AddButtonViewHolder。

这将导致执行落入else 的情况,并且您的masterList[position - 1] 逻辑最终将查询索引-1。

要解决此问题,请使用视图类型而不是使用 is 检查子类。基类RecyclerView.ViewHolder 有一个getItemViewType() 方法,无论你从适配器返回什么,它都会返回给你。由于视图类型逻辑是在您的基本适配器类中定义的,因此无论使用哪种具体实现类型,这都是相同的。

if (holder.itemViewType == TYPE_ADD_BUTTON) {
    (holder as AddButtonViewHolder).onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}

【讨论】:

  • 非常感谢我接受了这个问题,但问题应该更好。再次感谢
猜你喜欢
  • 2010-09-20
  • 2012-12-08
  • 2016-07-21
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 2013-04-24
相关资源
最近更新 更多