左侧3个tab切换右侧fragment
时间: 2023-07-28 12:39:17 浏览: 91
左侧3个tab切换右侧fragment的实现,可以使用Android中的Fragment和TabLayout控件。
首先,在XML布局文件中,可以使用TabLayout控件来布局左侧的3个tab,同时使用FrameLayout控件作为右侧fragment的容器。如下所示:
```xml
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabItem
android:id="@+id/tab_item_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 1"/>
<android.support.design.widget.TabItem
android:id="@+id/tab_item_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 2"/>
<android.support.design.widget.TabItem
android:id="@+id/tab_item_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 3"/>
</android.support.design.widget.TabLayout>
<FrameLayout
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
接下来,在Activity中,需要通过FragmentManager和FragmentTransaction来动态添加和切换右侧的fragment。如下所示:
```java
public class MainActivity extends AppCompatActivity {
private TabLayout mTabLayout;
private FrameLayout mFrameLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabLayout = findViewById(R.id.tab_layout);
mFrameLayout = findViewById(R.id.frame_layout);
// 添加默认的fragment
getSupportFragmentManager().beginTransaction()
.add(R.id.frame_layout, new Fragment1())
.commit();
// 设置tab切换监听器
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_layout, new Fragment1())
.commit();
break;
case 1:
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_layout, new Fragment2())
.commit();
break;
case 2:
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_layout, new Fragment3())
.commit();
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
```
在这个代码中,我们首先在Activity的onCreate方法中,通过findViewById方法获取到TabLayout和FrameLayout控件,并且添加了一个默认的fragment。然后,我们给TabLayout添加了一个TabSelectedListener,通过监听用户的tab切换行为,使用FragmentManager和FragmentTransaction动态地切换右侧的fragment。
阅读全文