在Kotlin中选择选项卡或在页面上滑动时如何加载片段

时间:2018-11-30 09:35:21

标签: android kotlin android-viewpager

  

活动

    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,并在单击单独的选项卡时用于加载不同的片段。但是问题是,当我单击选项卡时,片段未加载。当活动加载所有片段时,则片段不会改变。如何解决此问题?在视图分页器中选择选项卡时,我需要加载片段。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

请在onTabSelected()的每种情况下尝试viewpager.setCurrentItem(...)

答案 2 :(得分:0)

尝试一下

class NewPaymentActivity : AppCompatActivity() {
private val tabIcons = intArrayOf(R.mipmap.ic_launcher_round)//add tabs icons here

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_dashboard)


    viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(p0: Int) {
        }

        override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
        }

        override fun onPageSelected(position: Int) {


        }
    })
    setupViewPager(viewpager)
    tabs.setupWithViewPager(viewpager)
    setupTabIcons();

}

fun setupViewPager(viewPager: ViewPager) {
    val adapter = ViewPagerAdapter(supportFragmentManager)
    adapter.addFragment(PaymentDetailsFragment())
    viewPager.adapter = adapter
}

private fun setupTabIcons() {
    tabs.getTabAt(0)!!.setIcon(tabIcons[0])
}
}
  

ViewPagerAdapter

class ViewPagerAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm) {

private val mFragmentList:ArrayList<Fragment> = ArrayList()




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

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

fun addFragment(fragment: Fragment) {
    mFragmentList.add(fragment)
}
}