Android TabHost如何实现顶部选项卡

Xenia ·
更新时间:2024-09-20
· 744 次阅读

用TabHost 来实现顶部选项卡,上代码:activity_main.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:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TabHost android:id="@+id/tabMenu" android:layout_width="match_parent" android:layout_height="0dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> <LinearLayout android:id="@+id/tab3" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> </android.support.constraint.ConstraintLayout>

主方法MainActivity.java

package action.sun.com.tabhost; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TabHost; public class MainActivity extends AppCompatActivity { private TabHost tabhost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //得到TabHost对象实例 tabhost =(TabHost) findViewById(R.id.tabMenu); //调用 TabHost.setup() tabhost.setup(); //创建Tab标签 tabhost.addTab(tabhost.newTabSpec("one").setIndicator("红色").setContent(R.id.tab1)); tabhost.addTab(tabhost.newTabSpec("two").setIndicator("黄色").setContent(R.id.tab2)); tabhost.addTab(tabhost.newTabSpec("three").setIndicator("黄色").setContent(R.id.tab3)); tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { Log.d("xxx", "onTabChanged: ="+s); if (s.equals("one")){ //可是让viewpage的视图显示出来 //viewPager.setCurrentItem(0); }else if (s.equals("two")){ ////可是让viewpage的视图显示出来 // viewPager.setCurrentItem(1); } } }); } }

实现效果

您可能感兴趣的文章:Android开发之TabHost选项卡及相关疑难解决方法Android TabHost选项卡标签图标始终不出现的解决方法android FragmentTabhost实现导航分页Android 中 TabHost与ViewPager结合实现首页导航效果Android组件必学之TabHost使用方法详解Android组件TabHost实现页面中多个选项卡切换效果Android程序开发之自定义设置TabHost,TabWidget样式android TabHost(选项卡)的使用方法



tabhost 选项卡 Android

需要 登录 后方可回复, 如果你还没有账号请 注册新账号