【问题标题】:lateinit property adapter has not been initialized in Kotlin4Android在 Kotlin4Android 中没有初始化 lateinit 属性适配器
【发布时间】:2017-12-27 04:31:05
【问题描述】:

我在fragmentactivity 中创建了RecyclerView,一切正常,但是当我从activityinterfacenotifyDataSetChanged()adapter 时,我收到一个错误“ lateinit 属性adapter 尚未初始化" 但我已经initialized adapter

    class BuildingListFragment : Fragment(), MainActivity.EditInterface {


    lateinit var adapter: BuildingListAdapter

    private var mListener: OnFragmentInteractionListener? = null

    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_building_list, container, false)
    }

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

        val buildingList = ArrayList<BuildingDetailModel>()

        val alphaList = arrayOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
                "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "z")
        for (i in alphaList.indices) {

            val building = BuildingDetailModel()
            building.buildingName = alphaList[i] + " Building"
            buildingList.add(building)

        }

        //initialize adapter
        adapter = BuildingListAdapter(buildingList)
        // RV_Building_List.layoutManager = LinearLayoutManager(context, LinearLayout.VERTICAL, false)
        RV_Building_List.adapter = adapter

        RV_Building_List.layoutManager = object : LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false) {
            override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State) {
                super.onLayoutChildren(recycler, state)
                //TODO if the items are filtered, considered hiding the fast scroller here
                val firstVisibleItemPosition = findFirstVisibleItemPosition()
                if (firstVisibleItemPosition != 0) {
                    // this avoids trying to handle un-needed calls
                    if (firstVisibleItemPosition == -1)
                    //not initialized, or no items shown, so hide fast-scroller
                    {
                        fastscroller.visibility = View.GONE
                    }
                    return
                }
                val lastVisibleItemPosition = findLastVisibleItemPosition()
                val itemsShown = lastVisibleItemPosition - firstVisibleItemPosition + 1
                //if all items are shown, hide the fast-scroller
                fastscroller.visibility = if (adapter.itemCount > itemsShown) View.VISIBLE else View.GONE
            }
        }
        fastscroller.setRecyclerView(RV_Building_List)
        fastscroller.setViewsToUse(R.layout.recycler_view_fast_scroller__fast_scroller, R.id.fastscroller_bubble, R.id.fastscroller_handle)

    }

    override fun editClickFromMainActivity() {
        // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.

        //at this line error  is lateinit property adapter has not been initialized
        if (adapter.getIsSelected()) adapter.setIsSelected(false) else adapter.setIsSelected(true)
    }

    override fun onDetach() {
        super.onDetach()
        mListener = null
    }

    override fun onResume() {
        super.onResume()

    }

    interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        fun onFragmentInteraction(uri: Uri)
    }

    companion object {

        // TODO: Rename and change types and number of parameters
        fun newInstance(): BuildingListFragment {
            val fragment = BuildingListFragment()
            return fragment
        }
    }
}

我的主要活动

    class MainActivity : AppCompatActivity() {

    private val mOnNavigationItemSelectedListener =
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.navigation_list -> {
                        val fragment = BuildingListFragment.Companion.newInstance();
                        addFragment(fragment, R.anim.slide_re_in, R.anim.slide_re_out)
                        return@OnNavigationItemSelectedListener true
                    }
                    R.id.navigation_map -> {
                        val fragment = BuildingMapFragment.Companion.newInstance();
                        addFragment(fragment, R.anim.slide_in, R.anim.slide_out)
                        return@OnNavigationItemSelectedListener true
                    }
                }
                false
            }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

        val fragment = BuildingListFragment.Companion.newInstance()
        addFragment(fragment, R.anim.slide_re_in, R.anim.slide_re_out)

        iv_Add.setOnClickListener {
            var intent = Intent(this, AddBuildingMapsActivity::class.java)
            startActivity(intent)
        }
        iv_edit.setOnClickListener {
            (BuildingListFragment.newInstance() as EditInterface).editClickFromMainActivity()
        }
    }


    /**
     * add/replace fragment in container [framelayout]
     */
    private fun addFragment(fragment: Fragment, slide_re_in: Int, slide_re_out: Int) {

        supportFragmentManager
                .beginTransaction()
                .setCustomAnimations(slide_re_in, slide_re_out)
                .replace(R.id.fragmentContainer, fragment, null)//fragment.javaClass.getSimpleName()
                .addToBackStack(null)//fragment.javaClass.getSimpleName()
                .commit()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        Log.e("TAG", "TAG")
    }

    interface EditInterface {
        fun editClickFromMainActivity()
    }
}

请帮我解决这个问题 谢谢..

【问题讨论】:

  • 分享你的毕业作品。
  • // RxJava compile 'io.reactivex.rxjava2:rxjava:2.1.3' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' // 数据绑定 kapt "com.android.databinding: compiler:3.0.1" // Dagger 2 kapt 'com.google.dagger:dagger-compiler:2.14.1' compile 'com.google.dagger:dagger:2.14.1' compile 'io.nlopez.smartlocation:rx: 3.3.1'
  • 您能否也包括活动代码?我感觉你在创建视图之前调用了editClickFromMainActivity()
  • 我搜索了分配但没有得到更多,我认为 recycleview 需要在片段中设置像这样的 recyclerView.adapter = your_adapter 适配器。试试这个并仔细检查你的代码可能是你犯了一点矿工错误。
  • 我已经添加了我的 MainActivity..

标签: android kotlin android-recyclerview kotlin-android-extensions


【解决方案1】:

您的问题是,当在主活动行中调用单击处理程序时,您正在创建片段的新实例

(BuildingListFragment.newInstance() as EditInterface).editClickFromMainActivity()

您需要在当前屏幕上的实际片段实例上调用该方法。有多种方法可以解决这个问题,但我认为目前最安全的方法是做类似

iv_edit.setOnClickListener {
    val fragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as? BuildingListFragment
    fragment?.editClickFromMainActivity()
}

尽管这意味着您还必须在.replace(R.id.fragmentContainer, fragment, null) 行的addFragment 中使用相同的FRAGMENT_TAGFRAGMENT_TAG 而不是null

【讨论】:

  • 谢谢......这对我有用......你的一个帮助我如何在活动和片段之间使用接口
  • @umeshbaldaniya 也许这会有所帮助:guides.codepath.com/android/… - 如果没有,请创建一个新问题
猜你喜欢
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 2019-12-29
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 1970-01-01
相关资源
最近更新 更多