【问题标题】:How to replace fragment inside ViewPager and change toolbar如何替换 ViewPager 中的片段并更改工具栏
【发布时间】:2020-07-09 11:22:04
【问题描述】:

我在其中一个应用程序中发现了一个有趣的功能,我想重复一下。该应用程序具有 ViewPager 和 TabLayout 以及内部的一堆片段。 在第一个片段上有一个按钮img1

,按下它,片段被另一个img2替换

当 ads_banner 被移除并且工具栏被替换时, 当向右和向后滑动时,它显示fragment1,请告诉我如何做到这一点。这是我已经写的:

主活动

class MainActivity : AppCompatActivity() {

    private var mAdView: AdView? = null

    @SuppressLint("ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val adRequest = AdRequest.Builder().build()
        mAdView = findViewById(R.id.adView)
        mAdView!!.loadAd(adRequest)

        initTab()

    }

    fun initTab() {
        tab_layout.addTab(tab_layout.newTab().setIcon(R.drawable.image1)
        tab_layout.addTab(tab_layout.newTab().setIcon(R.drawable.image2)
        tab_layout.addTab(tab_layout.newTab().setIcon(R.drawable.image3)

        tab_layout.tabGravity = TabLayout.GRAVITY_FILL

        val adapter = MyPagerAdapter(supportFragmentManager, tab_layout.tabCount)
        pager.adapter = adapter

        pager.offscreenPageLimit = 2

        pager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tab_layout))

        tab_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                pager.currentItem = tab.position
                if (tab.position == 0) {
                    tab_layout.getTabAt(0)!!.setIcon(R.drawable.image1_focus)
                }
                if (tab.position == 1) {
                    tab_layout.getTabAt(1)!!.setIcon(R.drawable.image2_focus)
                }
                if (tab.position == 2) {
                    tab_layout.getTabAt(2)!!.setIcon(R.drawable.image3_focus)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                if (tab.position == 0) tab_layout.getTabAt(0)!!.setIcon(R.drawable.image1)
                if (tab.position == 1) tab_layout.getTabAt(1)!!.setIcon(R.drawable.image2)
                if (tab.position == 2) tab_layout.getTabAt(2)!!.setIcon(R.drawable.image3)
            }

            override fun onTabReselected(tab: TabLayout.Tab) {

            }
        })
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fitsSystemWindows="true"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@color/transparent"
        app:adSize="SMART_BANNER"
        app:adUnitId="@string/banner_key"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        style="@style/MyToolbar"
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:layout_marginTop="2dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/adView"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <TextView
            android:id="@+id/toolbar_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:fontFamily="@font/sf_pro_display_regular"
            android:textColor="@color/black"
            android:textSize="24sp"
            tools:layout_editor_absoluteX="206dp"
            tools:layout_editor_absoluteY="7dp" />

    </androidx.appcompat.widget.Toolbar>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/tab_layout"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#fff"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:tabBackground="@drawable/tab_color_selector"
        app:tabIndicatorColor="#2196F3"
        app:tabIndicatorGravity="top"
        app:tabIndicatorHeight="4dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

MyPagerAdapter

class MyPagerAdapter(fm: FragmentManager, internal var mNumOfTabs: Int) : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {

        when (position) {
            0 -> {
                return RootFragment()
//                return Fragment1()
            }
            1 -> {
                return Fragment2()
            }
            2 -> {
                return Fragment3()
            }
        }
    }

    override fun getCount(): Int {
        return mNumOfTabs
    }
}

片段1

class Fragment1: Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_1, container, false)
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
            btnfr1.setOnClickListener {
            val trans = fragmentManager!!.beginTransaction()
            trans.replace(R.id.root_frame, Fragment4())
            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            trans.addToBackStack(null)
            trans.commit()
        }
    }

根片段

class RootFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.root_fragment, container, false)
        val transaction = fragmentManager!!.beginTransaction()
       
        transaction.replace(R.id.root_frame, Fragment1())
        transaction.commit()
        return view
    }

}

root_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_frame" >

</FrameLayout>

在 Fragment1 中,只有调用 Fragment4 的按钮。试着在这里做https://www.codexpedia.com/android/android-viewpager-fragment-swap/ 原来是用Fragment4替换Fragment1,但是刷的时候不知道怎么重置Fragment4,也不明白怎么替换Toolbar和去除广告。

【问题讨论】:

    标签: android kotlin android-fragments android-viewpager fragment


    【解决方案1】:

    诀窍在于RootFragment 是第 0 个索引上的片段,您需要做的是使用通过childFragmentManager 的片段事务将原始片段显示为RootFragment 的子片段。

    这样,您可以替换 RootFragment 的子级,而无需在 ViewPager 中实际替换 RootFragment 本身。

    【讨论】:

      【解决方案2】:

      您需要在 MyPagerAdapter 中实现 createFragment 和 getItemCount 方法,以将片段实例作为页面提供给 ViewPager。 修改MyPagerAdapter类如下图并测试:

      class MyPagerAdapter(fm: FragmentManager, internal var mNumOfTabs: Int) : FragmentStatePagerAdapter(fm) {
      
      override fun getItemCount(): Int = mNumOfTabs
      
      override fun createFragment(position: Int): Fragment {
          when (position) {
              0 -> {
                  return RootFragment()
              }
              1 -> {
                  return Fragment2()
              }
              2 -> {
                  return Fragment3()
              }
          }
      } 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 1970-01-01
        • 2014-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多