Android,Kotlin:通过底部导航栏切换片段会导致错误

时间:2018-05-27 15:48:53

标签: android kotlin fragment reload

该应用程序启动完全正常,如下图所示。但它看起来很荒谬"通过单击底部导航栏切换到其他片段后。例如:应用程序启动正常(如下图所示),但如果我单击底部导航栏的第二个按钮,然后单击底部导航栏的第一个按钮返回相同的片段,则仅显示一半的spinner2和我的RecyclerView被隐藏了。这里有什么问题?请帮助解决这个问题。

app启动图片: enter image description here

通过单击底部导航栏切换后的

图片。 enter image description here

qponFragment.kt

class qponFragment : Fragment() {

    var database = FirebaseDatabase.getInstance()
    var myRef = database.getReference("SUBMIT")


    var countryloaded = ""
    var cityloaded = ""

    lateinit var spinnerOne : Spinner
    lateinit var spinnerTwo : Spinner

    val countryArray = arrayOf("選擇地區","香港","澳門","台灣")
    val taiwanArray = arrayOf("選擇城市","臺北市","新北市","桃園市","臺中市","臺南市","高雄市","基隆市","新竹市","嘉義市","新竹縣","苗栗縣","彰化縣","南投縣","雲林縣","嘉義縣","屏東縣","宜蘭縣","花蓮縣","臺東縣","澎湖縣","金門縣","連江縣")
    //val japanArray = arrayOf("選擇城市","東京","大阪","名古屋")
    var tempArray = mutableListOf<String>()

    //var databaseRef: DatabaseReference?=null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {



        //databaseRef = FirebaseDatabase.getInstance().reference

        // Inflate the layout for this fragment
        setHasOptionsMenu(true)

        return inflater.inflate(R.layout.fragment_qpon, container, false)

    }

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

        qponRecyclerView.layoutManager = LinearLayoutManager(context)
        qponRecyclerView.adapter = QponAdapter()

        val location = Location(activity!!)

        spinnerOne = view?.findViewById(R.id.spinner1) as Spinner
        spinnerTwo = view?.findViewById(R.id.spinner2) as Spinner


        //SpinnerOne
        spinnerOne.adapter = ArrayAdapter<String>(activity, R.layout.item, countryArray)

        //SpinnerTwo
        var dataAdapter = ArrayAdapter<String>(activity,  R.layout.item, tempArray)
        spinnerTwo.setAdapter(dataAdapter)

        spinnerOne.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

                var countrySeleccted:String = parent?.getItemAtPosition(position).toString()
                //println(textItem)

                if (countrySeleccted == "香港") {

                    location.saveCountry(countrySeleccted)
                    location.saveCity("empty")
                    //println(location.loadCountry())
                    //hide
                    spinnerTwo.setVisibility(View.GONE)
                    qponRecyclerView.setVisibility(View.VISIBLE)
                }

                else if (countrySeleccted == "澳門") {

                    location.saveCountry(countrySeleccted)
                    location.saveCity("empty")
                    //println(location.loadCountry())

                    //hide
                    spinnerTwo.setVisibility(View.GONE)
                    qponRecyclerView.setVisibility(View.VISIBLE)
                }

                else if (countrySeleccted == "台灣") {

                    location.saveCountry(countrySeleccted)
                    tempArray.clear()
                    tempArray.addAll(taiwanArray)
                    dataAdapter.notifyDataSetChanged()

                    //show
                    spinnerTwo.setVisibility(View.VISIBLE)
                    qponRecyclerView.setVisibility(View.GONE)
                }

                else {

                }

            }
        }

        //hide spinner2
        spinnerTwo.setVisibility(View.GONE)

        spinnerTwo.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                var citySelected: String = parent?.getItemAtPosition(position).toString()

                if (citySelected=="選擇城市"){

                }
                else {
                    location.saveCity(citySelected)
                    //println(location.loadCountry())
                    qponRecyclerView.setVisibility(View.VISIBLE)
                    //println("kkkkkkkkkkkkkkkk")
                    println(citySelected)
                }
            }
        }

        //check sharedPre data
        if (location.loadCountry() != "empty") {
            println(location.loadCountry())
            //println(location.loadCity())

            countryloaded = location.loadCountry()

            if (countryloaded == "香港") {
                spinnerOne.setSelection(1, true)
            }
            else if (countryloaded == "澳門") {
                spinnerOne.setSelection(2, true)
            }
            else if (countryloaded == "台灣") {
                spinnerOne.setSelection(3, true)

                cityloaded = location.loadCity()
                val indexNumber:Int = taiwanArray.indexOf(cityloaded)
                //println(indexNumber)
                if (indexNumber != -1) {
                    tempArray.clear()
                    tempArray.addAll(taiwanArray)
                    dataAdapter.notifyDataSetChanged()
                    spinnerTwo.setSelection(indexNumber, false)

                }
            }
            else {
                qponRecyclerView.setVisibility(View.GONE)
            }
        }
        else {
            qponRecyclerView.setVisibility(View.GONE)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {

        super.onCreateOptionsMenu(menu, inflater)
        inflater!!.inflate(R.menu.qpon_menu, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        val id = item?.getItemId()
        when (id) {
            R.id.item1 -> createToastMessage("Selected item 1")
            R.id.item2 -> createToastMessage("Selected item 2")
        }
        return true
    }

    private fun createToastMessage(message: String) {
        Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
    }




    inner class QponAdapter: RecyclerView.Adapter<qponFragment.QponCustomViewHolder>() {

        var listOfTutorial = TutorialList().list



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

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QponCustomViewHolder {

            val layoutInflater = LayoutInflater.from(parent.context)
            val cellForRow = layoutInflater.inflate(R.layout.qpon_layout, parent, false)
            return qponFragment.QponCustomViewHolder(cellForRow)

        }

        override fun onBindViewHolder(holder: qponFragment.QponCustomViewHolder, position: Int) {

            var videoName = listOfTutorial[position].name
            var videoImage = listOfTutorial[position].image
            var videoLink = listOfTutorial[position].youtubeLink

            holder.itemView.startDate.text = videoName
            holder.itemView.enddate.text = videoLink

        }
    }

    class QponCustomViewHolder(v: View): RecyclerView.ViewHolder(v) {

    }


}

控制台的结果:

05-27 23:35:35.143 32734-32734/? I/com.gph.qpon: Not late-enabling -Xcheck:jni (already on)
05-27 23:35:35.416 32734-32734/? W/com.gph.qpon: Unexpected CPU variant for X86 using defaults: x86
05-27 23:35:36.884 32734-32734/com.gph.qpon I/com.gph.qpon: The ClassLoaderContext is a special shared library.
05-27 23:35:37.108 32734-32734/com.gph.qpon W/com.gph.qpon: Suspending all threads took: 161.965ms
05-27 23:35:37.808 32734-32734/com.gph.qpon W/com.gph.qpon: JIT profile information will not be recorded: profile file does not exits.
05-27 23:35:37.811 32734-32734/com.gph.qpon I/chatty: uid=10094(com.gph.qpon) identical 10 lines
05-27 23:35:37.811 32734-32734/com.gph.qpon W/com.gph.qpon: JIT profile information will not be recorded: profile file does not exits.
05-27 23:35:38.107 32734-32734/com.gph.qpon D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
05-27 23:35:38.146 32734-32734/com.gph.qpon D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
05-27 23:35:38.269 32734-32734/com.gph.qpon V/FA: Cancelling job. JobID: 1286666166
05-27 23:35:38.277 32734-32734/com.gph.qpon V/FA: Registered activity lifecycle callback
05-27 23:35:38.280 32734-32734/com.gph.qpon I/FirebaseInitProvider: FirebaseApp initialization successful
05-27 23:35:38.281 32734-32734/com.gph.qpon I/InstantRun: starting instant run server: is main process
05-27 23:35:38.358 32734-32752/com.gph.qpon V/FA: Collection enabled
    App package, google app id: com.gph.qpon, 1:580019907416:android:f13bd2cc37b8f29d
05-27 23:35:38.358 32734-32752/com.gph.qpon I/FA: App measurement is starting up, version: 11910
05-27 23:35:38.359 32734-32752/com.gph.qpon I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
    To enable faster debug mode event logging run:
      adb shell setprop debug.firebase.analytics.app com.gph.qpon
05-27 23:35:38.359 32734-32752/com.gph.qpon D/FA: Debug-level message logging enabled
05-27 23:35:38.523 32734-32734/com.gph.qpon V/FA: onActivityCreated
05-27 23:35:38.568 32734-32752/com.gph.qpon V/FA: Connecting to remote service
05-27 23:35:38.608 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
05-27 23:35:38.609 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
05-27 23:35:38.684 32734-32752/com.gph.qpon V/FA: Connection attempt already in progress
05-27 23:35:39.005 32734-32756/com.gph.qpon W/com.gph.qpon: Unsupported class loader
05-27 23:35:39.022 32734-32756/com.gph.qpon I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
    Selected remote version of com.google.android.gms.firebase_database, version >= 6
05-27 23:35:39.176 32734-32756/com.gph.qpon W/com.gph.qpon: Unsupported class loader
05-27 23:35:39.320 32734-32734/com.gph.qpon I/System.out: 台灣
05-27 23:35:39.320 32734-32756/com.gph.qpon W/com.gph.qpon: Skipping duplicate class check due to unsupported classloader
05-27 23:35:39.449 32734-32758/com.gph.qpon D/NetworkSecurityConfig: No Network Security Config specified, using platform default
05-27 23:35:39.481 32734-32734/com.gph.qpon D/OpenGLRenderer: HWUI GL Pipeline
05-27 23:35:39.537 32734-32752/com.gph.qpon V/FA: Connection attempt already in progress
05-27 23:35:39.606 32734-32752/com.gph.qpon V/FA: Activity resumed, time: 104368397
05-27 23:35:39.698 32734-32752/com.gph.qpon I/FA: Tag Manager is not found and thus will not be used
05-27 23:35:39.774 32734-32752/com.gph.qpon D/FA: Logging event (FE): screen_view(_vs), Bundle[{firebase_event_origin(_o)=auto, firebase_screen_class(_sc)=MainActivity, firebase_screen_id(_si)=-5988656651441943046}]
05-27 23:35:39.947 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/graphics/FontFamily;-><init>()V (light greylist, reflection)
    Accessing hidden method Landroid/graphics/FontFamily;->addFontFromAssetManager(Landroid/content/res/AssetManager;Ljava/lang/String;IZIII[Landroid/graphics/fonts/FontVariationAxis;)Z (light greylist, reflection)
    Accessing hidden method Landroid/graphics/FontFamily;->addFontFromBuffer(Ljava/nio/ByteBuffer;I[Landroid/graphics/fonts/FontVariationAxis;II)Z (light greylist, reflection)
    Accessing hidden method Landroid/graphics/FontFamily;->freeze()Z (light greylist, reflection)
    Accessing hidden method Landroid/graphics/FontFamily;->abortCreation()V (light greylist, reflection)
    Accessing hidden method Landroid/graphics/Typeface;->createFromFamiliesWithDefault([Landroid/graphics/FontFamily;II)Landroid/graphics/Typeface; (light greylist, reflection)
05-27 23:35:40.287 32734-32752/com.gph.qpon V/FA: Connection attempt already in progress
05-27 23:35:40.588 32734-32760/com.gph.qpon I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
    android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
05-27 23:35:40.588 32734-32760/com.gph.qpon I/OpenGLRenderer: Initialized EGL, version 1.4
05-27 23:35:40.588 32734-32760/com.gph.qpon D/OpenGLRenderer: Swap behavior 1
05-27 23:35:40.604 32734-32760/com.gph.qpon D/EGL_emulation: eglCreateContext: 0xec604980: maj 2 min 0 rcv 2
05-27 23:35:40.608 32734-32745/com.gph.qpon I/com.gph.qpon: Background concurrent copying GC freed 9787(823KB) AllocSpace objects, 2(40KB) LOS objects, 49% free, 2MB/5MB, paused 1.295ms total 525.335ms
05-27 23:35:40.666 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:40.755 32734-32734/com.gph.qpon I/System.out: 臺南市
05-27 23:35:40.794 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:41.866 32734-32760/com.gph.qpon I/OpenGLRenderer: Davey! duration=1140ms; Flags=1, IntendedVsync=104369627325154, Vsync=104369643991820, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=104369658095247, AnimationStart=104369658270247, PerformTraversalsStart=104369658295247, DrawStart=104369691217247, SyncQueued=104369698042247, SyncStart=104369716740247, IssueDrawCommandsStart=104369817322247, SwapBuffers=104370695723247, FrameCompleted=104370787021247, DequeueBufferDuration=265000, QueueBufferDuration=9950000, 
05-27 23:35:41.892 32734-32752/com.gph.qpon D/FA: Connected to remote service
05-27 23:35:41.893 32734-32752/com.gph.qpon V/FA: Processing queued up service tasks: 4
05-27 23:35:41.913 32734-32734/com.gph.qpon W/InputMethodManager: Ignoring onBind: cur seq=361, given seq=360
05-27 23:35:41.914 32734-32734/com.gph.qpon I/Choreographer: Skipped 68 frames!  The application may be doing too much work on its main thread.
05-27 23:35:42.284 32734-32760/com.gph.qpon I/OpenGLRenderer: Davey! duration=1509ms; Flags=1, IntendedVsync=104369694884664, Vsync=104370828217952, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=104370834439247, AnimationStart=104370834490247, PerformTraversalsStart=104370834506247, DrawStart=104370974064247, SyncQueued=104371020262247, SyncStart=104371020345247, IssueDrawCommandsStart=104371020509247, SwapBuffers=104371156415247, FrameCompleted=104371204379247, DequeueBufferDuration=1583000, QueueBufferDuration=13778000, 
05-27 23:35:44.908 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/View;->getTransitionAlpha()F (light greylist, reflection)
05-27 23:35:44.981 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden field Landroid/view/View;->mViewFlags:I (light greylist, reflection)
05-27 23:35:44.984 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/View;->setTransitionAlpha(F)V (light greylist, reflection)
05-27 23:35:44.986 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/ViewGroup;->suppressLayout(Z)V (light greylist, reflection)
05-27 23:35:44.988 32734-32734/com.gph.qpon W/com.gph.qpon: Accessing hidden method Landroid/view/View;->setLeftTopRightBottom(IIII)V (light greylist, reflection)
05-27 23:35:46.580 32734-32734/com.gph.qpon W/com.gph.qpon: JNI critical lock held for 25.695ms on Thread[1,tid=32734,Runnable,Thread*=0xf05f4000,peer=0x740091f0,"main"]
05-27 23:35:46.610 32734-32734/com.gph.qpon W/com.gph.qpon: JNI critical lock held for 19.723ms on Thread[1,tid=32734,Runnable,Thread*=0xf05f4000,peer=0x740091f0,"main"]
05-27 23:35:46.628 32734-32734/com.gph.qpon I/System.out: 台灣
05-27 23:35:46.776 32734-32734/com.gph.qpon W/com.gph.qpon: JNI critical lock held for 21.868ms on Thread[1,tid=32734,Runnable,Thread*=0xf05f4000,peer=0x740091f0,"main"]
05-27 23:35:46.975 32734-32734/com.gph.qpon I/System.out: 臺南市
05-27 23:35:47.401 32734-32752/com.gph.qpon V/FA: Inactivity, disconnecting from the service
05-27 23:35:51.999 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:52.427 32734-32760/com.gph.qpon I/chatty: uid=10094(com.gph.qpon) RenderThread identical 1 line
05-27 23:35:52.607 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:53.013 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:53.046 32734-32734/com.gph.qpon I/System.out: 基隆市
05-27 23:35:53.304 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:53.661 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:35:58.679 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:00.619 32734-32734/com.gph.qpon I/System.out: 台灣
05-27 23:36:01.017 32734-32734/com.gph.qpon I/System.out: 基隆市
05-27 23:36:03.000 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:03.371 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:03.554 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:07.340 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:07.467 32734-32760/com.gph.qpon I/chatty: uid=10094(com.gph.qpon) RenderThread identical 1 line
05-27 23:36:07.969 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:10.939 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:11.199 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:11.359 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)
05-27 23:36:12.997 32734-32760/com.gph.qpon I/chatty: uid=10094(com.gph.qpon) RenderThread identical 2 lines
05-27 23:36:13.165 32734-32760/com.gph.qpon D/EGL_emulation: eglMakeCurrent: 0xec604980: ver 2 0 (tinfo 0xd5bff0f0)

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private var mFirebaseAnalytics: FirebaseAnalytics? = null

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.navigation_qpon -> {
                //message.setText(R.string.title_qpon)
                actionBarIcon(R.drawable.ic_title_black)
                createQponFragment()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_me-> {
                //message.setText(R.string.title_me)
                actionBarIcon(R.drawable.logged)
                createMeFragment()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_tool -> {
                //message.setText(R.string.title_tool)
                actionBarIcon(R.drawable.logged)
                createToolFragment()
                return@OnNavigationItemSelectedListener true
            }
            R.id.navigation_tutorial -> {
                //message.setText(R.string.title_tutorial)
                actionBarIcon(R.drawable.tutorial)
                createTutorialFragment()
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

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

        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)

        actionBarIcon(R.drawable.ic_title_black)


        createQponFragment()
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)
    }

    fun actionBarIcon(imageName:Int) {

        setSupportActionBar(findViewById(R.id.my_toolbar))
        my_toolbar.setLogo(imageName)

        if (imageName == R.drawable.ic_title_black) {
            my_toolbar.setTitle("")
        }

        if (imageName == R.drawable.logged) {

            my_toolbar.setTitle("login name")

        }
        if (imageName == R.drawable.tutorial) {

            my_toolbar.setTitle("Tutorial")

        }


    }

    val manager = supportFragmentManager



    fun createQponFragment() {
        val transaction = manager.beginTransaction()
        val fragment = qponFragment()
        transaction.replace(R.id.fragmentholder,fragment)
        transaction.addToBackStack(null)
        transaction.commit()


    }

    fun createMeFragment() {
        val transaction = manager.beginTransaction()
        val fragment = meFragment()
        transaction.replace(R.id.fragmentholder,fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }

    fun createToolFragment() {
        val transaction = manager.beginTransaction()
        val fragment = toolFragment()
        transaction.replace(R.id.fragmentholder,fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }

    fun createTutorialFragment() {
        val transaction = manager.beginTransaction()
        val fragment = tutorialFragment()
        transaction.replace(R.id.fragmentholder,fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }
}

0 个答案:

没有答案