美文网首页
Tablayout(使用带图片和文字样式)+ViewPager

Tablayout(使用带图片和文字样式)+ViewPager

作者: 嘿_叫我小王 | 来源:发表于2019-10-24 11:24 被阅读0次

最终效果图


a.png

xml布局:

<androidx.viewpager.widget.ViewPager
        android:id="@+id/vp_product"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_product"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:tabIndicatorHeight="0dp" />

app:tabIndicatorHeight="0dp"---------TabLayout 下划线(Indicator)宽度


java代码:

private void initView() {
        mTabProduct = (TabLayout) findViewById(R.id.tab_product);
        mVpProduct = (ViewPager) findViewById(R.id.vp_product);
        
        //将fragment装进列表中
        fragmentList = new ArrayList<>();
        fragmentList.add(new ProductFragment());    //产品
        fragmentList.add(new CompanyFragment());    //公司
        fragmentList.add(new TalkFragment());    //沟通
        fragmentList.add(new MineFragment());    //我的

//向适配器穿fragment集合
        productAdapter = new ProductAdapter(getSupportFragmentManager(), fragmentList);
        mVpProduct.setAdapter(productAdapter);
//设置联动
        mTabProduct.setupWithViewPager(mVpProduct);

        //设置Tablayout效果
        for (int i = 0; i < productAdapter.getCount(); i++) {
            mTabProduct.getTabAt(i).setCustomView(getView(i));
        }
    }

    private View getView(int i) {

        View view = View.inflate(this, R.layout.tab_view, null);//布局里有一个textview和一个imageview
          //找控件        
        ImageView iv = view.findViewById(R.id.tab_iv);
        TextView tv = view.findViewById(R.id.tab_tv);
        switch (i) {
            case 0:
                iv.setImageResource(R.drawable.product_ig);
                tv.setText("产品");
                break;
            case 1:
                iv.setImageResource(R.drawable.product_ig);
                tv.setText("公司");
                break;
            case 2:
                iv.setImageResource(R.drawable.product_ig);
                tv.setText("沟通");
                break;
            case 3:
                iv.setImageResource(R.drawable.product_ig);
                tv.setText("我的");
                break;
        }
        return view;
    }

相关文章

网友评论

      本文标题:Tablayout(使用带图片和文字样式)+ViewPager

      本文链接:https://www.haomeiwen.com/subject/zlsrvctx.html