android - 在 Kotlin 中选择选项卡或滑动页面时如何加载 fragment

标签 android kotlin android-viewpager

Activity

    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) {

    }

}

Fragment

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
}

I'm using android ViewPager and use for different fragments to load when I click separate tabs. But the issue is that when I click tabs fragments are not loading. when the activity loading all the fragments are loaded .then fragments are not changing. How can I solve this issue?I need to load fragment when I select tab in view pager.

最佳答案

根据 FragmentStatePagerAdapter :

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.

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

我希望这可以在某种程度上帮助你:

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

关于android - 在 Kotlin 中选择选项卡或滑动页面时如何加载 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53554786/

相关文章:

Android 设置viewpager的第一项

android - 每次查看 FragmentStatePagerAdapter 中的 fragment 时执行代码

java - 如何在 JSON 对象响应中访问 JSONArray 内部的 JSONArray

java - 从将在 Android 应用程序中具有全局范围的代码中设置区域设置

android - 在适当的外部 map 应用程序中打开 KML/GPX 文件

kotlin - 使用Room查询时,没有记录怎么办?

Android 列表小部件和项目点击不起作用

Android Location.distanceTo(...) 和 Location.bearingTo(...) 没有返回正确的结果

android - travis ci 构建失败 - 原因 : PermGen space

android - RecyclerView ViewPager java.lang.NullPointerException android.support.v7.widget.RecyclerView$ItemAnimator$ItemHolderInfo.left