传递数据时的活动和片段生命周期

时间:2019-07-14 20:18:37

标签: android android-fragments android-activity

我正在创建一个用于学习的音乐播放器,并想使用接口和I将活动容器中的歌曲列表传递给与之关联的6个片段(即专辑,艺术家,歌曲,流派,播放列表,MyFiles)已使用共享首选项存储了歌曲列表,因为我不想为每个片段创建单独的光标。
但是由于我首先意识到,由于首先调用viewpageradapter会导致片段生命周期,并且初始化了其所有资源,因此遇到了与传递列表有关的错误。
现在,由于我认为是在活动生命周期结束时调用的权限处理程序,因此所有逻辑都是针对因已创建片段而浪费的歌曲列表编写的。因此,有时歌曲列表会显示为片段,有时却不会。
现在我有以下问题
1.我使用的方法错误吗?
2.还是我的代码需要更改?
3.在这种情况下,共享首选项是否正确?

MainActivity

class MainActivity : AppCompatActivity() {

    private val tabLayout by binder<TabLayout>(R.id.tabs)
    private val viewPager by binder<ViewPager>(R.id.viewpager)
    private var msongListener: OnSongReceivedListener? = null

    lateinit var readWriteSongPermissionHandler : RequestPermissionHandler
    var songList:MutableList<BeatDto> = mutableListOf()
    lateinit var songManager: SongManager
    var sharedPreferences: SharedPreferences? = null
    lateinit var editor: SharedPreferences.Editor
    var file= Environment.getDataDirectory()
    val storage_check_pref="intent_memory"
    val song_list_pref="intent_songs"
    var current_memory:Float=0.0f
    val context = this


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

        sharedPreferences = context.getSharedPreferences("beat_drop", Context.MODE_PRIVATE);

        if(sharedPreferences?.getString(storage_check_pref,"").equals("success")){
            current_memory=SongManager.megaBytesAvailable(file)
        }

        setPermissionsandGetSongDetails()
        setupViewPager(viewPager)
        changeSelectedTabSize(tabLayout,viewPager,this)
        tabLayout.setupWithViewPager(viewPager)

    }



    interface OnSongReceivedListener {
        fun onPassSongs(listSongs: MutableList<BeatDto>)
    }

    fun setAboutDataListener(listener: OnSongReceivedListener) {
        msongListener = listener
        msongListener?.onPassSongs(songList)
    }



    fun setupViewPager(viewPager: ViewPager){

        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(AlbumFragment(),"Albums")
        adapter.addFragment(ArtistFragment(),"Artists")
        adapter.addFragment(SongFragment(),"Songs")
        adapter.addFragment(GenreFragment(),"Genres")
        adapter.addFragment(PlaylistFragment(),"Playlists")
        adapter.addFragment(MyFileFragment(),"My Files")
        viewPager.adapter=adapter
        viewPager.currentItem = 3
        viewPager.setOffscreenPageLimit(6);
    }




    fun changeSelectedTabSize(tabLayout:TabLayout,viewPager: ViewPager, context: Context?){

        for(i in 0 until tabLayout.tabCount){
            val tab:TabLayout.Tab?= tabLayout.getTabAt(i)
            val tabTextView:TextView?=TextView(context)
            tab?.customView = tabTextView
            tabTextView?.layoutParams?.width=ViewGroup.LayoutParams.WRAP_CONTENT
            tabTextView?.layoutParams?.height=ViewGroup.LayoutParams.WRAP_CONTENT

            tabTextView?.text = tab?.text

            if(i==0){
                tabTextView?.textSize = 18f
            }

        }

            val listener:TabLayout.TabLayoutOnPageChangeListener=TabLayout.TabLayoutOnPageChangeListener(tabLayout)
            viewPager.addOnPageChangeListener(listener)
        tabLayout.addOnTabSelectedListener(object:TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                val vg:ViewGroup=tabLayout.getChildAt(0) as ViewGroup
                val vgTab:ViewGroup=vg.getChildAt(tab?.position!!) as ViewGroup
                val tabChildsCount:Int=vgTab.childCount
                for (i in 0 until tabChildsCount){
                    val tabViewChild:View=vgTab.getChildAt(i)
                        if (tabViewChild is TextView)
                            tabViewChild.setTextSize(35.0f)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
              val vg:ViewGroup=tabLayout.getChildAt(0) as ViewGroup
              val vgTab:ViewGroup=vg.getChildAt(tab!!.position) as ViewGroup
                val tabChildsCount:Int=vgTab.childCount
                for (i in 0 until tabChildsCount){
                    val tabViewChild:View=vgTab.getChildAt(i)
                    if (tabViewChild is TextView)
                        tabViewChild.textSize = 8f
                }
            }

            override fun onTabReselected(p0: TabLayout.Tab?) {
            }


        })
    }

    fun setPermissionsandGetSongDetails(){
        try {
            readWriteSongPermissionHandler= RequestPermissionHandler(this@MainActivity,
                permissions = setOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                listener = object: RequestPermissionHandler.Listener{
                    override fun onComplete(grantedPermissions: Set<String>, deniedPermissions: Set<String>) {
                        if(grantedPermissions.isNotEmpty()){
                            if (current_memory< SongManager.megaBytesAvailable(file)){
                                songManager= SongManager()
                                songList=songManager.getPlayList(context)
                                editor= sharedPreferences!!.edit()
                                editor.putString(storage_check_pref,"success")
                                editor.putString(song_list_pref, Gson().toJson(songList).toString())
                                editor.commit()
                            }else{
                                songList= Gson().fromJson(sharedPreferences?.getString(song_list_pref,""),
                                    Array<BeatDto>::class.java).toMutableList()
                            }

                        }else if(deniedPermissions.isNotEmpty()){
                            Toast.makeText(context, "Permission Denied Already", Toast.LENGTH_SHORT).show()
                        }

                    }

                    override fun onShowPermissionRationale(permissions: Set<String>): Boolean {
                        AlertDialog.Builder(this@MainActivity).setMessage("To able to Listen Music, we need Read and Write permission")
                            .setPositiveButton("OK") { _, _ ->
                                readWriteSongPermissionHandler.retryRequestDeniedPermission()
                            }
                            .setNegativeButton("Cancel") { dialog, _ ->
                                readWriteSongPermissionHandler.cancel()
                                dialog.dismiss()
                            }
                            .show()
                        return true
                    }

                    override fun onShowSettingRationale(permissions: Set<String>): Boolean {
                        AlertDialog.Builder(this@MainActivity).setMessage("Go Settings -> Permission. " + "Make SMS on and Storage on")
                            .setPositiveButton("Settings") { _, _ ->
                                readWriteSongPermissionHandler.requestPermissionInSetting()
                            }
                            .setNegativeButton("Cancel") { dialog, _ ->
                                readWriteSongPermissionHandler.cancel()
                                dialog.cancel()
                            }
                            .show()
                        return true
                    }
                })
            readWriteSongPermissionHandler.requestPermission()
        }catch (ex:Exception){
            ex.printStackTrace()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
                                            grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        readWriteSongPermissionHandler.onRequestPermissionsResult(requestCode, permissions,
            grantResults)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        readWriteSongPermissionHandler.onActivityResult(requestCode)
    }

    internal inner class ViewPagerAdapter(manager: FragmentManager):FragmentPagerAdapter(manager){

        private val mFragmentList=ArrayList<Fragment>()
        private val mFragmentTitleList=ArrayList<String>()

        override fun getItem(p0: Int): Fragment {
            return mFragmentList[p0]
        }

        override fun getCount(): Int {
          return mFragmentList.size
        }

        fun addFragment(fragment:Fragment,title:String){
            mFragmentList.add(fragment)
            mFragmentTitleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return mFragmentTitleList[position]
        }


    }
}


SongFragment

class SongFragment : Fragment(){
    lateinit var recyclerView:RecyclerView
    lateinit var songAdapter: SongAdapter
    lateinit var songManager: SongManager
    var songList:MutableList<BeatDto> = mutableListOf()
    lateinit var readWriteSongPermissionHandler : RequestPermissionHandler
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view:View = inflater.inflate(R.layout.fragment_song, container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        recyclerView= view.findViewById(R.id.rr_songs)
        recyclerView.layoutManager=LinearLayoutManager(activity,LinearLayoutManager.VERTICAL,false)
        val spacingInPixels = resources.getDimensionPixelSize(R.dimen.mtrl_card_spacing)
        recyclerView.addItemDecoration(SpacesItemDecoration(spacingInPixels))
        recyclerView.adapter=songAdapter
        recyclerView.setHasFixedSize(true)
    }

    override fun onResume() {
        super.onResume()
        val mActivity = activity as MainActivity
        // mActivity.setAboutDataListener(this)
        mActivity.setAboutDataListener(object : MainActivity.OnSongReceivedListener {
            override fun onPassSongs(listSongs: MutableList<BeatDto>) {
                songList=listSongs
            }
        })
        songAdapter= SongAdapter(songList)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        readWriteSongPermissionHandler.onActivityResult(requestCode)
    }



}

0 个答案:

没有答案