接下來要實作跳轉之後的activty連接著viewpager跟tabitem去對應到相對的fragment
首先先跳轉到一個新的activity
<Button
android:id="@+id/next"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="next"/>
binding.next.setOnClickListener {
start(FragmentActivity::class.java)
}
那這邊說一下這個start是我在第十天的時候有說道的baseactivity那今天使用的時候發現了一個bug,修改完後應該是長這樣
protected fun start(next: Class<*>, bundle: Bundle?, finished: Boolean) {
val intent = Intent(this, next)
if(bundle == null)intent.putExtras(Bundle())
else intent.putExtras(bundle)
startActivity(intent)
if (finished) this.finish()
}
intent到的next應該要是我上面傳入的建構值而不是新增一個
那接著是新的activity的xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewmodel"
type="com.example.myapplication.FragmentViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"/>
</com.google.android.material.tabs.TabLayout>
</LinearLayout>
</layout>
再來是activity
class FragmentActivity : BaseActiivity(){
private val fragmentViewModel by lazy {
initViewModel(application , FragmentViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityFragmentBinding>(this,R.layout.activity_fragment)
binding.lifecycleOwner = this
binding.viewmodel = fragmentViewModel
}
}
跳轉之後就長這樣啦