Home > Mobile >  Kotlin (android studio) - changing tab by clicking doesn't change button on selected fragment,
Kotlin (android studio) - changing tab by clicking doesn't change button on selected fragment,

Time:05-08

I'm new to Kotlin and Android programming.

I Have 2 tabs using TabLayout and ViewPager2. In my main activity xml I have edit text widget. When I enter text and push ENTER the program needs to take the 'value' of the 'key' from edit text and add it as a button in the two tabs (fragments). Now, if I'm in the first tab - I can't seem to add button to the secont one. So I tried to add the button only after selecting the second tab, but clicking the tab seems to not work where swiping to the other tab works as planned.

Please help me to:

  1. Editing another fragment where its now in 'focus'
  2. fixing the clicking/swiping problem described.

Thanks!

My MainActivity.kt:

    class MainActivity : AppCompatActivity() {
        //declare all collections of barcode, items and changes
        var mConstantBarcodeMap = Constants.constantBarcodeMap
        private var usedBarcodeItems = mutableMapOf<String,String>()

        // declare binding object for all layouts
        private lateinit var bindingMain : ActivityMainBinding

        // declare tab and viewpager2 instances for building tabbed application
        private lateinit var tabLayout : TabLayout
        private lateinit var viewPager2 : ViewPager2

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

            // make binding object for all views
            bindingMain = ActivityMainBinding.inflate(layoutInflater)
            val viewMain = bindingMain.root
            setContentView(viewMain)

            getWindow().setBackgroundDrawableResource(R.drawable.background_iphone2);

            //get tab layout and viewPager2 from xml file
            tabLayout = findViewById(R.id.tab_layout)
            viewPager2 = findViewById(R.id.view_pager_2)
            val adapter = ViewPagerAdapter(supportFragmentManager, lifecycle)
            viewPager2.adapter = adapter

            TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
                when (position) {
                    0 -> tab.text = "Add"
                    1 -> tab.text = "Remove"
                }
            }.attach()

            // declare tab selected listener
            tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    tabChanged(tabLayout.selectedTabPosition)
                }
                override fun onTabUnselected(tab: TabLayout.Tab) {}
                override fun onTabReselected(tab: TabLayout.Tab) {}
            })

            // Make edit text listener
            val editTextInput = findViewById<EditText>(R.id.edit_text_input)
            editTextInput.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                    actionWithTextAfterEnter()
                    return@OnKeyListener true
                }
                false
            })
        }

            // method to add Button to addFragment
        private fun actionWithTextAfterEnter() {
                when (tabLayout.selectedTabPosition) {
                0 -> addTabActions()
                1 -> removeTabActions()
            }
        }

        private fun tabChanged(numOfTab: Int) {
            when (numOfTab) {
                0 -> switchedToAddTab()
                1 -> {
                    val isNull = (findViewById<LinearLayout>(R.id.ll_fragment_remove) != null)
                    Toast.makeText(this, isNull.toString(), Toast.LENGTH_SHORT).show()
                    if (findViewById<LinearLayout>(R.id.ll_fragment_remove) != null) {
                        switchedToRemoveTab()
                    }
                }
            }
        }

        private fun switchedToAddTab() {
            return
        }

        private fun switchedToRemoveTab() {
            val layout = findViewById<LinearLayout>(R.id.ll_fragment_remove)
            // removes all widget from add fragment
            layout.removeAllViews()
            // remake all widget to add fragment from collection
            for (value in usedBarcodeItems.values) {
                layout.addView(createButton(value))
            }
        }

        private fun addTabActions() {
            // checking if barcode is in mConstantBarcodeMap
            val etText : String = bindingMain.editTextInput.text.toString()
            val barcode = etText.dropLast(1)
            val isInBarcodeMap : Boolean =  mConstantBarcodeMap.containsKey(barcode)
            val isInBarcodeItemMap: Boolean = usedBarcodeItems.containsKey(barcode)
            val layout = findViewById<LinearLayout>(R.id.ll_fragment_add)

            if (isInBarcodeMap && !isInBarcodeItemMap) {
                usedBarcodeItems[barcode] = mConstantBarcodeMap[barcode].toString()
               // removes all widget from add fragment
                layout.removeAllViews()
                // remake all widget to add fragment from collection
                for (value in usedBarcodeItems.values) {
                    layout.addView(createButton(value))
                }
            } else if (isInBarcodeMap && isInBarcodeItemMap) {
                showWarningToast("This Item is Already on the List!")
            } else if (!isInBarcodeMap) {
                showWarningToast("This Item is not in Barcode List!")
            }
            bindingMain.editTextInput.text.clear()
        }

        private fun removeTabActions() {
            return
        }

        private fun createButton(buttonText : String) : Button {
            // declare and configure button widget
            val buttonItem = MaterialButton(this)

            val params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
                LinearLayoutCompat.LayoutParams.MATCH_PARENT,
                LinearLayoutCompat.LayoutParams.WRAP_CONTENT)
            params.setMargins(20, 10, 20, 10)
            buttonItem.layoutParams = params
            buttonItem.text = buttonText
            buttonItem.textSize = 20f
            buttonItem.setTextColor(Color.BLACK)
            buttonItem.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow_500))

            return buttonItem
        }

        private fun showWarningToast(warning: String) {
            Toast.makeText(this,warning,Toast.LENGTH_LONG).show()
        }

    }

Recording of app:

https://imgur.com/oM9T5Ak

notice the true/false toast:

Toast.makeText(this, isNull.toString(), Toast.LENGTH_SHORT).show()

CodePudding user response:

Maybe you need some changes in the adapter code of viewPager Let me share my code Here With tab layout and fragment

Here is the TabAdapter code

class TabAdapter : FragmentStateAdapter {

    var fragments = arrayListOf<Fragment>()

    constructor(fragmentActivity: FragmentActivity, fragments: ArrayList<Fragment>) : super(fragmentActivity) {
        this.fragments = fragments
    }
    constructor(fragmentManager: FragmentManager, lifecycle: Lifecycle, fragments: ArrayList<Fragment>) : super(
        fragmentManager,
        lifecycle
    ) {
        this.fragments = fragments
    }

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

    override fun createFragment(position: Int): Fragment {
        return fragments[position]
    }
}

Attaching Fragment

private fun setUpViewPager(fragments: ArrayList<Fragment>, titles: ArrayList<String>) {
    fragmentAdapter = TabAdapter(this, fragments)
    bindingMain.viewPager2.offscreenPageLimit = fragments.size
    bindingMain.viewPager2.adapter = fragmentAdapter
    bindingMain.viewPager2.isSaveEnabled = false
    TabLayoutMediator(bindingMain.tabLayout, bindingMain.viewPager2) { tab, position ->
        tab.text = titles[position]
    }.attach()
}

  • Related