【问题标题】:How to load the fragments when the tab is selected or page is swiped in Kotlin在 Kotlin 中选择选项卡或滑动页面时如何加载片段
【发布时间】:2018-11-30 09:35:21
【问题描述】:

活动

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

【问题讨论】:

  • 您的onFragmentInteraction 是做什么的?看起来它是唯一一个调用 setCurrentItem 并始终设置为第二个片段的地方?
  • 它用于一旦我单击该特定片段上的按钮,它将通过界面调用该方法。即使我单击标签片段也不会调用。仅在第一次加载所有片段时。
  • 对,那么你应该尝试在onTabSelected()中添加viewpager.setCurrentItem(position)
  • 已添加但未加载片段 ViewPagerAdapter.getItem 方法也调用但片段未运行。
  • 当你说它没有加载时,你的意思是你可以滑动但它只是空的?

标签: android kotlin android-viewpager


【解决方案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
    }
}

【讨论】:

    【解决方案2】:

    请在 onTabSelected() 的每个条件下尝试 viewpager.setCurrentItem(...)

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

        猜你喜欢
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多