简体   繁体   中英

A fragment with 2 tabs without viewpager

[Image of my drawer menu][1]I have an app with a navigation drawer with fragments. Now I want that one fragment has 2 tabs inside of it with each tab another fragment. I search several days for an example but didn't find one in Kotlin Code. It is always an activity with tabs with fragments but never a fragment with 2 tabs and each a fragment. Who can help me?

Searching for an example en this for weeks. I only want to change tab by a click on it,not swipe.

Mainactivity.kt

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    // variable nodig vor de taalinstelling
    lateinit var mTaalVar : String // hier maken we de variabele GLOBAL
    //lateinit var mGuidVar : String // hier maken we de variabele GLOBAL
    lateinit var uniqueId: String // hier maken we de variabele GLOBAL

    // deze variabel hebben we nodig voor onze GUID die we geven in globalvarID
    val positiveButtonClick = { dialog: DialogInterface, _: Int ->
       // Toast.makeText(applicationContext, android.R.string.yes, Toast.LENGTH_LONG).show()
    }
    // variabelen om et kijken of de app voor de eerste keer open gaat
    var PRIVATE_MODE = 0
    val PREF_NAME = "myPreferences"
    val PREF_NAME1 = "myPreferences1"

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

        //Deze moet hier staan anders klopt de vertaling niet
        setContentView(R.layout.activity_main)


        // dit moet er staan anders wordt de title en optionbuttons niet getoond
        setSupportActionBar(idToolbar)

        // variabele  declareren om te kijken of het de eerste keer is dat de app draait
        val sharePref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
       // val sharePref1: SharedPreferences = getSharedPreferences(PREF_NAME1, PRIVATE_MODE)

        //Hier halen we de waarde uit de sharedprefferences PREF_NAME
        val firstTime = sharePref.getBoolean(PREF_NAME, false)

        if (firstTime == false) {

            //val text5 = " Boolean False nog geen GUID"                        //debugger
           // val duration5 = Toast.LENGTH_LONG                                 //debugger
            //val toast5 = Toast.makeText(applicationContext, text5, duration5) //debugger
            //toast5.show()                                                     //debugger

            // hier zetten we de boolean op true en slaan we op in sharedPreferences (PREF_Name)
            val editor = sharePref.edit()
            editor.putBoolean(PREF_NAME, true)
            editor.apply()

            // hier slaan we de GUID op in sharedPreferences
             uniqueId = UUID.randomUUID().toString() // hier geven we een guid mee
             val editor1 = getSharedPreferences("Settings", Context.MODE_PRIVATE).edit() //"Settings" is de file waar we de key"My_Guid" met waarde uniqueId in opslaan
             editor1.putString("My_Guid", uniqueId)
             editor1.apply()

            //hier halen de taal op uit het toestel
            val CurrentLang = Locale.getDefault().language

            // showStartDialog()  //debugger

            // hier zetten we om naar hoofdletters om de webpagina's correct te kunnen laden
            if(CurrentLang == "fr") {
                setLocate("FR")
                recreate()
            } else if (CurrentLang == "nl"){
                setLocate("NL")
                recreate()
            } else if (CurrentLang == "de"){
                setLocate("DE")
                recreate()
            } else {
                setLocate("EN")
                recreate()
            }
            //hier laden we de indexpage in de contentpagina en moeten we de taal EN meegeven annders gaat he fout bij de eerste kker dat je de app installeert

            webviewContent.loadUrl("https://www.rectusoft.com/app_depaddel/index.php?taal=EN" )

            // Enable javascript in web view
            //webviewContent.settings.javaScriptEnabled=true

            // Enable zooming in web view
            webviewContent.settings.setSupportZoom(true)
            webviewContent.settings.builtInZoomControls = true
            webviewContent.settings.displayZoomControls = true
        }
        else {

            //taal
            loadLocate()

            // Ophalen van de GUID uit de file settings1
            val sharePref1: SharedPreferences = getSharedPreferences("Settings", PRIVATE_MODE)
            val guid = sharePref1.getString("My_Guid", "LEEG")

            //val text5 = " Boolean True    GUID = " +  guid + "  Taalinstelling:  " + mTaalVar
           // val duration5 = Toast.LENGTH_LONG
            //val toast5 = Toast.makeText(applicationContext, text5, duration5)
           // toast5.show()
            //hier laden we de indexpage in de contentpagina
            webviewContent.loadUrl("https://www.rectusoft.com/app_depaddel/index.php?taal=" + mTaalVar)
            // Enable zooming in web view
            webviewContent.settings.setSupportZoom(true)
            webviewContent.settings.builtInZoomControls = true
            webviewContent.settings.displayZoomControls = true
        }


        val toggle = ActionBarDrawerToggle(
            this, drawer_layout, idToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )

        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()
        nav_view.setNavigationItemSelectedListener(this)

}


    override fun onBackPressed() {
        // code voor "bij het klikken van de backbutton komt het dialogscherm met de vraag om af te sluiten"
        val alertDialog1 = AlertDialog.Builder(this)
            //set icon
            .setIcon(android.R.drawable.ic_dialog_alert)
            //set title
            .setTitle(R.string.exit)
            //set message
            .setMessage(R.string.close)
            //set positive button
            .setPositiveButton(R.string.yes, DialogInterface.OnClickListener { dialog, _ ->
                //set what would happen when positive button is clicked
                finish()
            })
            //set negative button
            .setNegativeButton(R.string.no, DialogInterface.OnClickListener { _, _ ->
                //set what should happen when negative button is clicked
                Toast.makeText(applicationContext, R.string.nothing, Toast.LENGTH_LONG).show()
            })
            .show()
    }


    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_time_table -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_timetable , Toast.LENGTH_SHORT).show()
                // Handle the  load timetable action
                loadTimetable(fragTimetable = timetable_fragment())
            }
            R.id.nav_my_time_table -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_my_timetable , Toast.LENGTH_SHORT).show()
                // Handle the  load my timetable action
                loadMyTimetable(fragMyTimetable = my_timetable_fragment())
            }
            R.id.nav_my_teams_details -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_my_teams_details , Toast.LENGTH_SHORT).show()
                // Handle the  load my timetable action
                loadMyTeamsDetails(fragMyTeamsDetails = my_teams_details_fragment())

            }
            R.id.nav_top_scoring_player -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_top_scoring_player , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadTopscore(fragTopScore = top_score_fragment())
            }
            R.id.nav_rectusoft_league -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_rectusoft_league , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadLeague(fragLeague = league_fragment())
            }

            R.id.nav_division1 -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_division1 , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadDivision1(fragDivision1 = division1_fragment())
            }

            R.id.nav_division2 -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_division2 , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadDivision2(fragDivision2 = division2_fragment())
            }

            R.id.nav_division3 -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_division3 , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadDivision3(fragDivision3 = division3_fragment())
            }

            R.id.nav_ladies_division -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this, R.string.nav_divisionLadies , Toast.LENGTH_SHORT).show()
                // Handle the  load TOP SCORE LIST action
                loadDivisionLadies(fragDivisionLadies = divisionLadies_fragment())
            }
        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        //taal
        loadLocate()
        //Deze moet er staan anders krijg je geen optie menu op je scherm
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            //hieronder worden de acties gemaakt als op een optionmenu geklikt wordt
            R.id.opt_about -> {
                // Er wordt steeds een toast weergegeven als er op een menu-item geklikt wordt.
                Toast.makeText(this,  R.string.opt_about, Toast.LENGTH_SHORT).show()

                showStartDialog()

                return super.onOptionsItemSelected(item)
            }
            R.id.opt_language -> {
                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this,  R.string.opt_my_language , Toast.LENGTH_SHORT).show()

                //hier laden we de functie om het keuzemenu te tonen
                showChangeLang()

                return super.onOptionsItemSelected(item)
            }

            R.id.opt_my_teams -> {

                // Er wordt steeds een toast weergegeven als er op een menuitem geklikt wordt.
                Toast.makeText(this,  R.string.opt_my_teams, Toast.LENGTH_SHORT).show()
                //hier laden we het scherm 'language'
                loadMyTeams(fragMyTeams = my_teams_fragment())
                //getSupportActionBar()?.setTitle("My Teams")
                return super.onOptionsItemSelected(item)
            }
            else -> return super.onOptionsItemSelected(item)
        }

    }

    /*private fun loadAbout(fragAbout: about_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragAbout)
        fm.commit()
    }*/

    private fun loadMyTeams(fragMyTeams: my_teams_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragMyTeams)
        fm.commit()
    }

    private fun loadMyTeamsDetails(fragMyTeamsDetails: my_teams_details_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragMyTeamsDetails)
        fm.commit()
    }

    //Als frameLayout in het rood blijft staan is omdat je het vergeten bent aan te maken op de \layout\content_Main
    private fun loadTimetable(fragTimetable: timetable_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragTimetable)
        fm.commit()
    }

    private fun loadMyTimetable(fragMyTimetable: my_timetable_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragMyTimetable)
        fm.commit()
    }

    private fun loadTopscore(fragTopScore: top_score_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragTopScore)
        fm.commit()
    }

    private fun loadLeague(fragLeague: league_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragLeague)
        fm.commit()
    }

    private fun loadDivision1(fragDivision1: division1_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragDivision1)
        fm.commit()
    }

    private fun loadDivision2(fragDivision2: division2_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragDivision2)
        fm.commit()
    }

    private fun loadDivision3(fragDivision3: division3_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragDivision3)
        fm.commit()
    }

    private fun loadDivisionLadies(fragDivisionLadies: divisionLadies_fragment) {
        val fm = supportFragmentManager.beginTransaction()
        fm.replace(R.id.igFrameLayout, fragDivisionLadies)
        fm.commit()
    }


    private fun showStartDialog(){                                                                        //debugger
       val builder = AlertDialog.Builder(this)                                                            //debugger

        builder.setTitle("RECTUSOFT")                                                                          //debugger
        builder.setMessage(R.string.about_text)                                 //debugger
        builder.setPositiveButton("ok",DialogInterface.OnClickListener(function = positiveButtonClick))   //debugger
        builder.show()

       }

    //taalinstelingen
    private fun setLocate (Lang: String){

        val locale = Locale(Lang)
        Locale.setDefault(locale)
        val config = Configuration()
        config.locale = locale
        baseContext.resources.updateConfiguration(config, baseContext.resources.displayMetrics)

        val editor = getSharedPreferences("Settings", Context.MODE_PRIVATE).edit()
        editor.putString("My_Lang", Lang)
        editor.apply()
    }

    private fun loadLocate(){
        val sharedPreferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE)
        val language = sharedPreferences.getString("My_Lang", "EN")

        mTaalVar = language
        // val mApp = MyGlobalVar()
        //val mTaalVar = mApp.globalVarTaal
        setLocate(mTaalVar)
    }

    private fun showChangeLang(){

        val listItmes = arrayOf("Français","Nederlands","Deutsch","English")
        val mBuilder = AlertDialog.Builder( this@MainActivity)
        val title = mBuilder.setTitle(R.string.choos_your_language)

        mBuilder.setSingleChoiceItems(listItmes, -1) { dialog, which ->
            if(which == 0) {
                setLocate("FR")
                recreate()
                //finish()
            } else if (which == 1){
                setLocate("NL")
                recreate()
                // finish()
            } else if (which == 2){
                setLocate("DE")
                recreate()
                //finish()
            } else if (which == 3){
                setLocate("EN")
                recreate()
                // finish()
            }

            dialog.dismiss()
            System.runFinalizersOnExit(true)
        }
        val mDialog = mBuilder.create()
        mDialog.show()
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context="com.rectusoft.tournamentorganizerkdp.MainActivity"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

    <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

division1_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:title="@string/division_2" 
        android:id="@+id/tabLayout">

   <android.support.design.widget.TabLayout
           android:layout_width="378dp"
           android:layout_height="219dp"
           android:layout_marginTop="8dp" 
           app:layout_constraintTop_toTopOf="parent"
           android:layout_marginBottom="8dp" 
           app:layout_constraintBottom_toBottomOf="parent"
           app:layout_constraintStart_toStartOf="parent" 
           android:layout_marginLeft="8dp"
           android:layout_marginStart="8dp" 
           app:layout_constraintEnd_toEndOf="parent" 
           android:layout_marginEnd="8dp"
           android:layout_marginRight="8dp">

      <android.support.design.widget.TabItem
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Saturday"/>

      <android.support.design.widget.TabItem
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Sunday"/>

   </android.support.design.widget.TabLayout>

division1_fragment.kt

   class division1_fragment : Fragment() {


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

        val viewPager: ViewPager? = view?.findViewById<ViewPager>(R.id.viewPager)
        if (viewPager != null) {
            val adapter = ViewPagerAdapter(childFragmentManager)
            viewPager.adapter = adapter
        }
        return view
    }

}

division1_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

   <android.support.v4.view.ViewPager
           android:id="@+id/viewPager"
           android:layout_width="match_parent"
           android:layout_height="match_parent">

      <android.support.v4.view.PagerTabStrip
              android:id="@+id/pager_header"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_gravity="top"
              android:background="@color/colorPrimary"
              android:padding="13dp"/>

   </android.support.v4.view.ViewPager>

ViewPageAdapter.kt

class ViewPagerAdapter internal constructor(fm: FragmentManager) : FragmentPagerAdapter(fm) {

    private val COUNT = 3

    override fun getItem(position: Int): Fragment? {
        var fragment: Fragment? = null
        when (position) {
            0 -> fragment = FirstFragment()
            1 -> fragment = SecondFragment()
            2 -> fragment = ThirdFragment()
        }

        return fragment
    }

    override fun getCount(): Int {
        return COUNT
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return "Tab " + (position + 1)
    }
}




  [1]: https://i.stack.imgur.com/PXor9.jpg

What you're trying to accomplish

From the description of your problem, the real thing you're trying to accomplish is simply to have a TabHost inside a Fragment (as opposed to an Activity), because your Navigation Drawer takes you to a Fragment, likely replacing the currently displayed one.

What's the issue?

You've likely seen most TabHost examples implemented as an Activity that then hosts tabs which display fragments when tapped. In truth, there's nothing crazily special about what you describe.

What would I do?

I would personally use a ViewPager instead of a TabHost (you said you didn't want the swipe gesture, and there are ways to do that ), but regardless of your solution, a Fragment can display Child (also known as Nested) Fragments. The most important thing is to remember to use the correct FragmentManager (there's a getChildFragmentManager() method instead of the usual).

The method (As described by the documentation ):

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

Hopefully this drives you in the right direction, for now it's going to be up to you to test, implement, and debug your solution; these are some of the tools at your disposal.

When you implement this, don't hesitate to post concrete questions about your implementation if you find something not working as expected.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM