簡體   English   中英

如何在android中的選項卡布局中設置自定義選項卡

[英]How to set Custom tab in tab layout in android

活動_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:background="#ef9f9f"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabGravity="fill"
                app:tabMode="fixed" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>

// 主要活動:

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    public ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        View headerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
                .inflate(R.layout.custom_tab, null, false);

        final LinearLayout linearLayoutOne = (LinearLayout) headerView.findViewById(R.id.ll);
        final LinearLayout linearLayout2 = (LinearLayout) headerView.findViewById(R.id.ll2);
        final TextView text1 = (TextView) headerView.findViewById(R.id.tvtab1);
        final TextView text2 = (TextView) headerView.findViewById(R.id.tvtab2);
        tabLayout.getTabAt(0).setCustomView(linearLayoutOne);
        tabLayout.getTabAt(1).setCustomView(linearLayout2);


        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {

                if (tab.getText().equals("ONE")) {

                    text1.setVisibility(View.VISIBLE);
                } else {

                    text2.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

                if (tab.getText().equals("ONE")) {
                    text1.setVisibility(View.GONE);
                } else {
                    text2.setVisibility(View.GONE);
                }

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

}

這是我的代碼我想設置自定義選項卡就像我選擇第一個選項卡然后指示器和選項卡寬度或第一個選項卡的重量如果我們選擇第二個選項卡然后選擇第一個選項卡我應該增加和第二個選項卡減少只顯示圖像而不是文本指標或權重應減少,第二個標簽文本和圖像應在以下位置可見:

我當前的屏幕:

在此處輸入圖片說明

在此您可以看到選項卡一被選中圖像並且文本可見選項卡第二未被取消選擇所以唯一的圖像是可見的沒有文本:

但我的預期標簽是這樣的:

在此處輸入圖片說明

當我們選擇選項卡時查看此內容,然后選項卡的指示器和寬度增加,選項卡 2 減少請建議我如何實現這一點。thanx

您可以使用選項卡布局輕松實現自定義選項卡,試試這個:

public void setupTabView(){
    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        tabLayout.getTabAt(i).setCustomView(R.layout.custom_tab);
        TextView tab_name = (TextView) tabLayout.getTabAt(i).getCustomView().findViewById(R.id.txt_tab_name);
        tab_name.setText("" + tabNames[i]);
    }
}

並制作一個名為 custom_tab 的可繪制文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txt_tab_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="14sp" />

</RelativeLayout>

使用下面的代碼。它有兩個選項。 (i) 創建自定義 TabLayout (ii) 更改自定義 tablayout 文本顏色

(i) 自定義 TabLayout

 <TextView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/tab"
android:layout_width="match_parent"
android:textSize="15sp"
android:gravity="center"
android:textColor="@color/txtbox_text_color_darek"
android:layout_height="match_parent"
/>

源代碼是:

        TextView tabOne = (TextView) 
        LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("KPIs" + " ");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.alert_gray, 
        0);
        Objects.requireNonNull(tabLayout.getTabAt(4)).setCustomView(tabOne);

(二)改變顏色

     private void custom_tablayout_select_unselected_four(final TextView tabOne) {

     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (Objects.requireNonNull(tabLayout.getTabAt(4)).isSelected()) {
                tabOne.setTextColor(getResources().getColor(R.color.text_color_darkblue));
            } else {


      tabOne.setTextColor(getResources().getColor(R.color.txtbox_text_color_darek));
            }

        }

        @Override`
        public void onTabUnselected(TabLayout.Tab tab) {
            // tabOne.setTextColor(Color.GREEN);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // tabOne.setTextColor(Color.GREEN);
        }
    });

}

我從這里復制了解決方案,也許對你有用

 Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

   TabHost mTabHost = getTabHost();

   mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
           .setIndicator((""),getResources().getDrawable(R.drawable.mzl_05))
     .setContent(new Intent(this, NearBy.class)));
   mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
           .setIndicator((""),getResources().getDrawable(R.drawable.mzl_08))
     .setContent(new Intent(this, SearchBy.class)));
           mTabHost.setCurrentTab(0);
           mTabHost.getTabWidget().getChildAt(0).setLayoutParams(new
             LinearLayout.LayoutParams((width/2)-2,50));
      mTabHost.getTabWidget().getChildAt(1).setLayoutParams(new
                 LinearLayout.LayoutParams((width/2)-2,50));

你可以試試另一個代碼tabHost.getTabWidget().getChildAt(0).getLayoutParams().width = 50;

創建自定義選項卡布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@drawable/tab_text_color_selector"
        android:textSize="@dimen/medium_text"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_count"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_marginStart="4dp"
        android:background="@drawable/badge_background"
        android:gravity="center"
        android:textColor="@color/colorPrimary"
        android:textSize="@dimen/medium_text"
        android:textStyle="bold"
        android:visibility="gone" />
</LinearLayout>

tabTitles = new String[]{getString(R.string.main_tab_call), getString(R.string.main_tab_chat), getString(R.string.main_tab_contact)};

  private void setupTabIcons() {
    for (int i = 0; i < tabTitles.length; i++) {
        mTabLayout.getTabAt(i).setCustomView(prepareTabView(i));
    }
}


private View prepareTabView(int pos) {
    View view = getLayoutInflater().inflate(R.layout.custom_tab, null);
    TextView tv_title = view.findViewById(R.id.tv_title);
    TextView tv_count = view.findViewById(R.id.tv_count);
    tv_title.setText(tabTitles[pos]);
    return view;
}

下面的代碼在android中的自定義tablayout。

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        createViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        createTabIcons();
    }
    private void createTabIcons() {

        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("Tab 1");
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_dash26, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("Tab 2");
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_category, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);

        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText("Tab 3");
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_order, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
    }

    private void createViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new Fragment1(), "Tab 1");
        adapter.addFrag(new Fragment2(), "Tab 2");
        adapter.addFrag(new Fragment3(), "Tab 3");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

您可以在此處完整代碼: https : //code-android-example.blogspot.com/2019/11/custom-tablayout-android.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM