现在很多主流的应用都喜欢底部几个导航按钮,点击切换不同的页面。通常我们可以自己底部写按钮,然后点击不同的按钮自己来控制切换fragment。今天我们用fragmentTabHost来快速的实现这个功能:
<?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/main_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"></FrameLayout>
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#999"></android.support.v4.app.FragmentTabHost>
</LinearLayout>
这是主界面布局,fragment显示在frameLayout中,底部是一个FramentTabHost。
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import com.example.wpf.dsyx.R;
import com.example.wpf.dsyx.fragment.Fragment1;
import com.example.wpf.dsyx.fragment.Fragment2;
import com.example.wpf.dsyx.fragment.Fragment3;
import com.example.wpf.dsyx.fragment.Fragment4;
import com.example.wpf.dsyx.tools.L;
import java.util.List;
import java.util.Map;
public class Test extends AppCompatActivity implements TabHost.OnTabChangeListener {
private String texts[] = {"首页", "消息", "好友", "广场"};
private Class fragmentArray[] = {Fragment1.class, Fragment2.class, Fragment3.class, Fragment4.class};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_test);
FragmentTabHost fragmentTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
fragmentTabHost.setup(this, getSupportFragmentManager(), R.id.main_content);
for (int i = 0; i < 4; i++) {
TabHost.TabSpec spec = fragmentTabHost.newTabSpec(texts[i]).setIndicator(getView(i));
fragmentTabHost.addTab(spec, fragmentArray[i], null);
}
fragmentTabHost.setOnTabChangedListener(this);
}
private View getView(int i) {
//取得布局实例
View view = LayoutInflater.from(this).inflate(R.layout.tabcontent, null, false);
//取得布局对象
ImageView imageView = (ImageView) view.findViewById(R.id.image);
TextView textView = (TextView) view.findViewById(R.id.text);
//设置标题
textView.setText("sdfsdf");
return view;
}
@Override
public void onTabChanged(String tabId) {
L.i(tabId);
}
}
首先获取到FragmentTabHost 控件,调用setup方法。指定fragment的容器,底部有四个导航按钮,所以for循环四次,TabSpec spec = fragmentTabHost.newTabSpec(texts[i]).setIndicator(getView(i));
最后调用fragmentTabHost的addTab方法把tabspec添加到fragmentTabHost中,这样就完成了。要监听切换界面可以给fragmentTabHost添加setOnTabChangedListener。需要注意的是用这种方式每次切换界面都会调用oncreateView重绘。
创建四个spec对象指定视图