因为Tabhost已经不推荐使用了,现在一般都使用FragmentTabhost!因为Fragment是3.0才出现,为了避免3.0以下的使用不了,所以我们要用v4包来支持。
首先给出两个布局文件:
1、layout_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight ="0"
/>
</android.support.v4.app.FragmentTabHost>
</LinearLayout>
2、tab_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/image_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/text_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"/>
</LinearLayout>
下面给出代码:
MainActivity.class
public class MainActivity extends AppCompatActivity {
private FragmentTabHost mTabHost;
private LayoutInflater mInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
mInflater = LayoutInflater.from(this);
mTabHost = (FragmentTabHost) this.findViewById(android.R.id.tabhost);
mTabHost.setup(this,getSupportFragmentManager(), R.id.realtabcontent);
TabHost.TabSpec tabSpec = mTabHost.newTabSpec("home");
View view =null;
view = mInflater.inflate(R.layout.tab_indicate,null);
ImageView img = (ImageView) view.findViewById(R.id.image_icon);
TextView text = (TextView) view.findViewById(R.id.text_content);
img.setBackgroundResource(R.mipmap.ic_launcher);
text.setText("主页");
tabSpec.setIndicator(view);
mTabHost.addTab(tabSpec,HomeFragment.class,null);
}
}
另外还需要一个fragment
Homefragment.class
public class HomeFragment extends Fragment{
}
效果图:
至此,一个简单的FragmentTabhost的使用就完成了。不过只有一个home选项.需要多个可以调用上述代码重复添加。