Android Fragments Kotlin(android studio)-通过点击来更改选项卡不会更改选定片段上的按钮,而滑动到选项卡可以工作

nwlls2ji  于 2022-11-24  发布在  Android
关注(0)|答案(1)|浏览(170)

我是Kotlin和Android编程的新手。
我有两个使用TabLayout和ViewPager 2的选项卡。在我的主活动xml中,我有编辑文本小部件。当我输入文本并按ENTER键时,程序需要从编辑文本中获取“键”的“值”,并将其作为按钮添加到两个选项卡中(片段)。现在,如果我在第一个选项卡-我似乎不能添加按钮到第二个。所以我试图添加按钮后,才选择第二个选项卡,但是点击标签似乎不起作用,在那里滑动到其他标签按计划工作。
请帮助我:
1.正在编辑另一个片段,该片段现在处于“焦点”中
1.修复所述的点击/滑动问题。
谢谢你!
我的主要活动.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
注意真假吐司:
Toast.makeText(this, isNull.toString(), Toast.LENGTH_SHORT).show()

dsekswqp

dsekswqp1#

也许您需要在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()
}

相关问题