1

The following code is based by Android Studio Wizard 3.2.1 for creating Tabbed Activity.

There is a button1 on PlaceholderFragment1 connected Tab1, and a button2 on PlaceholderFragment2 connected Tab2

I hope to click button1 to switch to Tab2, and click button2 to switch to Tab1, How can I do ?

BTW, I have read How to change tab on button click in Android? and How to programmatically switch tabs using buttonclick in Android

Code

class MainActivity : AppCompatActivity() {

    private var mSectionsPagerAdapter: SectionsPagerAdapter? = null

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

        mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)


        container.adapter = mSectionsPagerAdapter

        container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
        tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))

    }


    inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            val fragment: Fragment
            when (position) {
                0 -> fragment = PlaceholderFragment1()  //Tab1
                1 -> fragment = PlaceholderFragment2()  //Tab2
                else -> throw IllegalArgumentException("Invalid section number")
            }
            return fragment
        }

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


    class PlaceholderFragment1 : Fragment() {

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

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
           button1.setOnClickListener {
               //Switch to Tab2
           }
        }
    }


    class PlaceholderFragment2 : Fragment() {

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

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            button2.setOnClickListener {
                //Switch to Tab1
            }
        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:tools="http://schemas.android.com/tools"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 android:id="@+id/main_content"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 android:fitsSystemWindows="true"
                                                 tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/appbar_padding_top"
            android:theme="@style/AppTheme.AppBarOverlay">


        <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            <android.support.design.widget.TabItem
                    android:id="@+id/tabItem"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tab_text_1"/>

            <android.support.design.widget.TabItem
                    android:id="@+id/tabItem2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/tab_text_2"/>

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>


</android.support.design.widget.CoordinatorLayout>

fragment_main1.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/constraintLayout"
                                             android:layout_width="match_parent"
                                             android:layout_height="match_parent"
                                            >


    <Button
            android:text="Button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button1"/>
</android.support.constraint.ConstraintLayout>

My way

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       ...

        setControl(view)
}


private fun setControl(view: View){
   button1.setOnClickListener {
             var viewPager=view.parent as ViewPager
             viewPager.setCurrentItem(1,true)
   }
}
ChamCham
  • 408
  • 1
  • 6
  • 16
HelloCW
  • 476
  • 10
  • 77
  • 178

2 Answers2

1

manually binding these events is not required...

you just have to setup the TabLayout with the Viewpager:

container.adapter = mSectionsPagerAdapter
tabs.setupWithViewPager(container);

then these events are being handled by the framework, in a rather convenient way.

PS: container is a rather unfortunate variable name for a ViewPager.

Martin Zeitler
  • 49,224
  • 12
  • 97
  • 156
1

I think you should use Livedata and ViewModel.

  • Create View Model class with livedata.
  • Observer Livedata in MainActivity.
  • Update livedata value from your fragment.

For example:

class TabChangerViewModel : ViewModel() {
    val colorResource = MutableLiveData<Int>()
    .........
}

In your MainActivity class:

val tabChangerViewModel = ViewModelProviders.of(this).get(TabChangerViewModel::class.java) // initialize view model

        tabChangerViewModel.colorResource.observe(this, android.arch.lifecycle.Observer {
        //mViewPager.setCurrentItem(it)
    })

Now update live data value from your fragment:

    val tabChangerViewModel = ViewModelProviders.of(activity).get(TabChangerViewModel::class.java) // initialize view model

tabChangerViewModel.colorResource.value = TAB_POSITION_WANT_TO_SELECT
Mitesh Vanaliya
  • 2,255
  • 21
  • 39