Kotlin (android studio) - 通过单击更改选项卡不会更改所选片段上的按钮,滑动到选项卡有效

Kotlin (android studio) - changing tab by clicking doesn't change button on selected fragment, where swiping to the tab works

我是 Kotlin 和 Android 编程的新手。

我有 2 个使用 TabLayout 和 ViewPager2 的选项卡。 在我的主要 activity xml 中,我有编辑文本小部件。当我输入文本并按 ENTER 时,程序需要从编辑文本中获取 'key' 的 'value' 并将其添加为两个选项卡(片段)中的按钮。 现在,如果我在第一个选项卡中 - 我似乎无法将按钮添加到第二个选项卡。 所以我尝试仅在选择第二个选项卡后添加按钮,但点击选项卡似乎不起作用,而滑动到另一个选项卡按计划工作。

请帮我:

  1. 正在编辑另一个片段,它现在位于 'focus'
  2. 修复所描述的 clicking/swiping 问题。

谢谢!

我的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()
        }

    }

应用录音:

https://imgur.com/oM9T5Ak

注意 true/false 吐司:

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

也许你需要修改一下viewPager的适配器代码 让我在这里分享我的代码 使用选项卡布局和片段

这是 TabAdapter 代码

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]
    }
}

附加片段

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()
}