使用FragmentTabHost 完成一个简单的底部导航栏

使用FragmentTabhost+Fragment实现一个底部导航栏
主布局:

   //放置Fragment
  <FrameLayout  android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/fragment">

    </FrameLayout>
    <android.support.v4.app.FragmentTabHost  android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content">

        <!--<FrameLayout-->
            <!--android:id="@+id/tabcontent"-->

            <!--android:layout_width="0dp"-->
            <!--android:layout_height="0dp"-->
            <!--android:layout_weight="0"-->
        <!--/>-->
    </android.support.v4.app.FragmentTabHost>

代码:

public class FragmentTabhost extends AppCompatActivity {
    private Class fragmentArray[] = {BlankFragment.class, BlankFragment1.class, BlankFragment2.class};

    private int mImageViewArray[] = {R.drawable.tag,R.drawable.thunder,R.drawable.umbrella};

    private String mTextviewArray[] = {"首页", "消息","更多"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_tabhost);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FragmentTabHost fg= (FragmentTabHost) findViewById(R.id.tabhost);
        fg.setup(this, getSupportFragmentManager(), R.id.fragment);
        int count = fragmentArray.length;
        //循环放置
        for(int i = 0; i < count; i++){
            TabHost.TabSpec tabSpec = fg.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            fg.addTab(tabSpec, fragmentArray[i], null);
        }
         //去掉了底部导航栏的间隔竖线
        fg.getTabWidget().setDividerDrawable(null);
    }
//给导航栏放置图片和标题
    private View getTabItemView(int index){
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_item_xml, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
        imageView.setImageResource(mImageViewArray[index]);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTextviewArray[index]);
        return view;
    }

}

选中变色就不在啰嗦了 使用FragmentTabHost 完成一个简单的底部导航栏_第1张图片

你可能感兴趣的:(android,布局,导航)