当前位置: 首页 > 知识库问答 >
问题:

如何在Kotlin中选择选项卡或刷页时加载片段

淳于俊迈
2023-03-14
    class NewPaymentActivity : AppCompatActivity(),SummaryFragment.OnFragmentInteractionListener,ReceiptDetailsFragment.OnFragmentInteractionListener{

    internal lateinit var viewpageradapter: ViewPagerAdapter //Declare PagerAdapter

    private var tabLayout: TabLayout? = null
    var viewPager: ViewPager? = null
    var toolbar: Toolbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_payment)
        viewpageradapter= ViewPagerAdapter(supportFragmentManager)

        viewPager = findViewById(R.id.viewPager) as ViewPager
        setupViewPager(viewPager!!)

        tabLayout = findViewById(R.id.tab_layout) as TabLayout
        tabLayout!!.setupWithViewPager(viewPager)

//      tabLayout!!.setSelectedTabIndicatorColor(getResources().getColor(R.color.t));
        tabLayout!!.setSelectedTabIndicatorHeight(0)




        val headerView = (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
                .inflate(R.layout.custom_tabs_for_payments, null, false)

        val receiptDetails = headerView.findViewById(R.id.tb_receipt_details) as TextView
        val paymentDetails = headerView.findViewById(R.id.tb_payment_details) as TextView
        val invoiceDetails = headerView.findViewById(R.id.tb_invoice_details) as TextView
        val summary = headerView.findViewById(R.id.tb_summary) as TextView

        receiptDetails.setTextColor(resources.getColor(R.color.white))
        val drawable = receiptDetails.getBackground() as GradientDrawable
        drawable.setColor(resources.getColor(R.color.received_payments))

        paymentDetails.setTextColor(resources.getColor(R.color.main))
        val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
        drawablepaymentDetails.setColor(resources.getColor(R.color.white))

        invoiceDetails.setTextColor(resources.getColor(R.color.main))
        val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
        drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

        summary.setTextColor(resources.getColor(R.color.main))
        val summarydrawable = summary.getBackground() as GradientDrawable
        summarydrawable.setColor(resources.getColor(R.color.white))

        tabLayout!!.getTabAt(0)!!.setCustomView(receiptDetails)
        tabLayout!!.getTabAt(1)!!.setCustomView(paymentDetails)
        tabLayout!!.getTabAt(2)!!.setCustomView(invoiceDetails)
        tabLayout!!.getTabAt(3)!!.setCustomView(summary)

        tabLayout!!.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {

                if(tab!!.position==0)
                {
                    receiptDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = receiptDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))
                }
                else if(tab!!.position==1)
                {
                    paymentDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = paymentDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails= receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))


                }
                else if(tab!!.position==2)
                {
                    invoiceDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = invoiceDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails= receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))


                }
                else if(tab!!.position==3)
                {
                    summary.setTextColor(resources.getColor(R.color.white))
                    val drawable = summary.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails = receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))
                }
                else {

                }

            }
            override fun onTabUnselected(tab:TabLayout.Tab?){
            }
            override fun onTabReselected(tab:TabLayout.Tab?) {
            }
        })


    }

    private fun setupViewPager(viewPager: ViewPager) {

        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(ReceiptDetailsFragment(), "Receipt Details")
        adapter.addFragment(PaymentDetailsFragment(), "Payment Details")
        adapter.addFragment(InvoiceDetailsFragment(), "Invoice Details")
        adapter.addFragment(SummaryFragment(), "Summary")
        viewPager.adapter = adapter



    }

    internal inner class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager) {

        private val mFragmentList = ArrayList<Fragment>()
        private val mFragmentTitleList = ArrayList<String>()

        override fun getItem(position: Int): Fragment {
            return mFragmentList[position]
        }

        override fun getCount(): Int {
            return mFragmentList.size
        }

        fun addFragment(fragment: Fragment, title: String) {
            mFragmentList.add(fragment)
            mFragmentTitleList.add(title)
        }

        override fun getPageTitle(position: Int): CharSequence {
            return mFragmentTitleList[position]
        }

    }

    override fun onFragmentInteraction(jsonObject: JSONObject) {
        //session intialization
        val myPreference = Session(this)
        myPreference.setJsonObject(jsonObject.toString())
        viewPager!!.setCurrentItem(1,true)


    }


    override fun onFragmentInteraction(uri: Uri) {

    }

}
class PaymentDetailsFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val rootView = inflater.inflate(R.layout.fragment_payment_details, container, false)

    val replacingLayout = rootView.findViewById(R.id.replacing_layout) as LinearLayout
    val viewPaymentCheque = activity!!.layoutInflater.inflate(R.layout.payment_details_cheques, null)
    Log.e("test Object","test")

    replacingLayout.addView(viewPaymentCheque)
    val myPreference = Session(activity!!)
    Log.e("test Object", myPreference.getJsonObject())
    if(myPreference.getJsonObject()!="") {

        var obj = JSONObject(myPreference.getJsonObject());
        Log.e("test Object", obj.toString())
    }



    return rootView
}

}

我使用android ViewPager,当我点击不同的标签时,使用不同的片段来加载。但问题是,当我单击选项卡时,片段没有加载。当活动加载时,所有的片段都被加载,那么片段就不会改变。我如何解决这个问题?我需要加载片断时,我选择选项卡在查看页。

共有1个答案

严升
2023-03-14

根据FragmentStatePagerAdapter:

当有大量页面时,这个版本的页导航更有用,更像是列表视图。当页面对用户不可见时,它们的整个片段可能会被销毁,只保持该片段的保存状态。与FragmentPagerAdapter相比,这使得分页器可以保持与每个访问页相关联的内存少得多,但在页之间切换时可能会增加开销。

因此,显然您的适配器实现不正确,getItem应该总是返回新的片段实例,因为它们可能无法在配置更改中存活,而viewpager负责它们的生命周期,并在必要时请求新的实例。也许这就是为什么你的特定片段没有在你滑动时加载的原因。

internal inner class ViewPagerAdapter(manager: FragmentManager) : FragmentStatePagerAdapter(manager) {

    override fun getItem(position: Int): Fragment {
        return when (position) {
            0 -> ReceiptDetailsFragment()
            1 -> PaymentDetailsFragment()
            2 -> InvoiceDetailsFragment()
            3 -> SummaryFragment()
            else -> throw IllegalArgumentException()
        }
    }

    override fun getPageTitle(position: Int): CharSequence {
        return when (position) {
            0 -> "Receipt Details"
            1 -> "Payment Details"
            2 -> "Invocie Details"
            3 -> "Summary"
            else -> throw IllegalArgumentException()
        }
    }

    override fun getCount(): Int {
        return 4
    }
}
 类似资料:
  • 我已经在我的片段中重写了以下方法:setUserVisibleHint 在fragment类中,变量设置为:private var isLoadOnce=false。 我有3个片段,问题是当我的活动popsup时,第一个片段是可见的,如果我单击最后一个选项卡,也就是第三个选项卡加载第三个片段,什么也不会发生,即web服务根本不会调用。

  • 问题内容: 我在内使用3 ,问题是我在和加载器中加载大数据。在这类设备上,它可以正常工作,但是在低端设备上,则需要很多时间。这主要是因为当我实现时,我将Fragments放在an中,这迫使片段在加载主活动时实例化。我需要的是它只是“加载”第一个片段(主要),而当用户使用时,加载另一个片段。它有什么办法做到这一点?这是我的页面 问题答案: Sun的上述方法对我不起作用(也许对您有用),但是我想我也将

  • 我有一个带有FragmentStateAdapter()适配器的viewpage er2。我还有一个带有4个选项卡的选项卡布局。我为所有选项卡使用单个片段。这被命名为AllOrdersTabb。在我的架构中,我只是发送不同的值来将不同的API数据加载到AllOrdersTab片段。当选择每个选项卡布局时,创建一个片段并首次为所有4个片段正常工作。之后,如果我刷回上一个选项卡,它就不会再次创建或刷新

  • 问题内容: 我有以下代码: MainActivity.java TabsPagerAdapter.java 我正在制作一个图书馆应用程序,其中导航是通过选项卡进行的,问题是每次我从第三个选项卡转到第一个或第一个至第三个时,选项卡的内容都在刷新,我想防止刷新,任何请帮助 ? 问题答案: 默认情况下,在滑动页面时会重新创建片段。为防止这种情况,您可以尝试以下三种方法之一: 1. 在您的片段中,呼叫。

  • 我在我的项目中使用并以片段形式显示数据。这是一个很棒的图书馆,工作很棒。每个片段都由一个学者的讲座组成,这些讲座是从web服务加载的。访问web服务的代码位于片段的方法中。目前,所有片段的数据在添加到时同时加载。我想知道是否只有当用户单击/滑动到特定的选项卡时才能加载片段的数据。不是一次什么都做。 当前的代码是相当标准的,我从提供的示例[android解决方案]中获得了帮助。1 为了确保Fragm