如何自定义单个选项卡?(更改背景颜色、指示器颜色和文本颜色)

11
在这个链接中:How do I apply a style programmatically? Kevin Grant 对这个问题进行了解释,但他代码中的上下文部分让我困惑。确切地说:
ctv = new CustomView(context, R.attr.tabStyleAttr);

在这段代码中,它说:上下文无法解析为变量。

我想给选项卡应用特定的样式,所以设置主题对我不起作用。当然,欢迎任何其他解决办法。

我尝试更改操作栏选项卡的背景颜色、指示器颜色和文本颜色。

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
{
    CustomView ctv;
    ctv = new CustomView(this, R.attr.tabStyleAttr);        
    tab.setCustomView(ctv);  
    mViewPager.setCurrentItem(tab.getPosition());
}

样式表.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Ab" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/abStyle</item> 
        <item name="@attr/actionBarTabStyle">@style/tabStyle</item>        
        <item name="android:actionBarTabTextStyle">@style/tabTextColor</item>
    </style>   

    <style name="abStyle" parent="@android:style/Widget.Holo.Light.ActionBar.Solid">
        <item name="android:background">@drawable/ab_solid_style</item>
        <item name="android:backgroundStacked">@drawable/ab_stacked_solid_style</item>
        <item name="android:backgroundSplit">@drawable/ab_bottom_solid_style</item>
        <item name="android:height">100dp</item>
    </style>    

    <style name="tabStyle" parent="@android:style/Widget.Holo.Light.ActionBar.TabView">

        <item name="android:background">@drawable/tab_indicator_ab_style</item>
    </style>

    <style name="tabTextColor" parent="@android:style/Widget.Holo.Light.ActionBar.TabText">
        <item name="android:textColor">@android:color/white</item>
    </style>



</resources>

MainActivity.java(onCreate)

public void onCreate(Bundle savedInstanceState)
    {       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        //set custom actionbar
        actionBar.setCustomView(R.layout.titlebar);
        //Displays the custom design in the actionbar
        actionBar.setDisplayShowCustomEnabled(true);
        //Turns the homeIcon a View     
        View homeIcon = findViewById(android.R.id.home);
        //Hides the View (and so the icon)
        ((View)homeIcon.getParent()).setVisibility(View.GONE);

        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
        {           
            @Override
            public void onPageSelected(int position)
            {
                    // When swiping between different app sections, select the corresponding tab.
                    // We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
                    actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++)
        {

            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            Tab tab = actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this);            
            actionBar.addTab(tab);
        }
    }

这是我想要制作的内容:

示例


使用Views后,新的结果如下:

使用Views

MainActivity.java

package com.example.android.effectivenavigation;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    //The viewpager displays on of the section at a time
    ViewPager mViewPager;

    public void onCreate(Bundle savedInstanceState)
    {       
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        //set custom actionbar
        actionBar.setCustomView(R.layout.titlebar);
        //Displays the custom design in the actionbar
        actionBar.setDisplayShowCustomEnabled(true);
        //Turns the homeIcon a View     
        View homeIcon = findViewById(android.R.id.home);
        //Hides the View (and so the icon)
        ((View)homeIcon.getParent()).setVisibility(View.GONE);


        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
        {           
            @Override
            public void onPageSelected(int position)
            {
                    // When swiping between different app sections, select the corresponding tab.
                    // We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
                    actionBar.setSelectedNavigationItem(position);
            }
        });
       /*final Tab firstTab = actionBar.newTab()
                .setText(mAppSectionsPagerAdapter.getPageTitle(0))
                .setTabListener(this)
                .setCustomView(R.id.nieuws_tab_layout);
        /*final Tab secondTab = actionBar.newTab()
                 .setText(mAppSectionsPagerAdapter.getPageTitle(1))
                 .setCustomView(R.id.nieuws_tab_layout);
        final Tab thirdTab = actionBar.newTab()
                .setText(mAppSectionsPagerAdapter.getPageTitle(2))
                .setCustomView(R.id.nieuws_tab_layout);

        actionBar.addTab(firstTab);
        actionBar.addTab(secondTab);
        actionBar.addTab(thirdTab);*/

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++)
        {
            if(i == 0)
            {
                final View firstCustomView = new CustomView(this);
                //firstCustomView.setBackgroundColor(Color.BLUE);
                Tab tab = actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this).setCustomView(R.layout.nieuws_tab_layout);
                actionBar.addTab(tab);
            }
            else
            {
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            Tab tab = actionBar.newTab().setText(mAppSectionsPagerAdapter.getPageTitle(i)).setTabListener(this);            
            actionBar.addTab(tab);
            }
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    {
        //CustomView ctv;
        //ctv = new CustomView(context, R.attr.tabStyleAttr);
        // When the given tab is selected, switch to the corresponding page in the ViewPager.
        //LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        //View tabView = inflater.inflate(R.layout.nieuws_tab_layout, null);
        //tabView.setBackgroundColor(0xFF00FF00);
        //tab.setCustomView(tabView);  
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
    {
    }

    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter 
    {
        public AppSectionsPagerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) 
        {
            switch (i)
            {
                case 0:
                    // The first section of the app is the most interesting -- it offers
                    // a launchpad into the other demonstrations in this example application.
                    return new LaunchpadSectionFragment();

                default:
                    // The other sections of the app are dummy placeholders.
                    Fragment fragment = new DummySectionFragment();
                    Bundle args = new Bundle();
                    args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
                    fragment.setArguments(args);
                    return fragment;
            }
        }

        @Override
        public int getCount()
        {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) 
        {
            switch(position)
            {
                case 0:
                {
                    return "Tab1";
                }
                case 1:
                {
                    return "Tab2";
                }
                case 2:
                {
                    return "Tab3";
                }
                default:
                {
                    return "Section " + (position + 1);
                }
            }
        }
    }
    public static class LaunchpadSectionFragment extends Fragment
    {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
        {
            View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);

            // Demonstration of a collection-browsing activity.
            rootView.findViewById(R.id.demo_collection_button).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view) 
                {
                    Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
                    startActivity(intent);
                }
            });

            // Demonstration of navigating to external activities.
            rootView.findViewById(R.id.demo_external_activity).setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    // Create an intent that asks the user to pick a photo, but using
                    // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
                    // the application from the device home screen does not return
                    // to the external activity.
                    Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
                    externalActivityIntent.setType("image/*");
                    externalActivityIntent.addFlags(
                    Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    startActivity(externalActivityIntent);
                }
            });
            return rootView;
        }
    }

    /**
     * A dummy fragment representing a section of the app, but that simply displays dummy text.
     */
    public static class DummySectionFragment extends Fragment
    {
        public static final String ARG_SECTION_NUMBER = "section_number";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
            Bundle args = getArguments();
            ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }
    public class CustomView extends View
    {
        public CustomView(Context context)
        {
            super(context, null);
        }
    } 
}

tab_layout.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" >

  <TextView
              android:id="@+id/nieuws_tab_layout"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"              
              android:text="@string/nieuws"
              android:gravity="center_vertical"
              android:layout_marginTop="15dp"
              android:textColor="@android:color/white"
              android:textStyle="bold"
              android:background="@android:color/black"
              />
</LinearLayout>

这是在Activity内部吗?尝试使用这个(似乎是您未声明的实例),而不是context。 - nKn
如果您也粘贴初始化选项卡和选项卡栏的代码,那么帮助您将更加容易。 - desseim
我以为TabHost扩展了与我使用的viewpager不同的活动,我还阅读了TabHost代码,它扩展了TabActivity而不是FragmentActivity。 - Shishi
你在问题中提到了操作栏; TabActivity / TabHost 是实现选项卡的另一种方式... - desseim
关于示例图片:选定的标签应该是什么样子?它应该与未选定时相同吗? - desseim
显示剩余5条评论
3个回答

7

在标签创建时,只需设置您的自定义视图,例如:

final Tab firstTab = actionBar.newTab()
                              .setText(mAppSectionsPagerAdapter.getPageTitle(0))
                              .setCustomView(R.id.custom_tab_view_red);
final Tab secondTab = actionBar.newTab()
                               .setText(mAppSectionsPagerAdapter.getPageTitle(1))
                               .setCustomView(R.id.custom_tab_view_blue);
// etc

actionBar.addTab(firstTab);
actionBar.addTab(secondTab);
// etc

inCreate()中。

您还需要在xml布局文件中定义与上述id对应的Views(而不是styles)。

或者,如果您想直接创建视图:

final View firstCustomView = new CustomView(this);
firstCustomView.setBackgroundColor(Color.BLUE);  // or with drawable or resource
final Tab firstTab = actionBar.newTab()
                              .setText(mAppSectionsPagerAdapter.getPageTitle(0))
                              .setCustomView(firstCustomView);
actionBar.addTab(firstTab);
// then same for other tabs, just with another color

以下信息仅供参考:

为了定义这样的视图,您需要为其指定一个Android Context。通常情况下,这是显示选项卡的Activity。 假设您在Activity中初始化选项卡,只需将Activity实例作为Context传递即可:

ctv = new CustomView(this, R.attr.tabStyleAttr);

如果是在Activity内部,或者例如:

ctv = new CustomView(getActivity(), R.attr.tabStyleAttr);

如果是从Fragment等内部进行设置,针对操作栏选项卡设置特定样式时,无需像您试图的那样编程创建自定义视图。首先需要了解一下操作栏,然后查看示例。如您所见,您可以在xml中指定选项卡样式。

In your manifest file, you can apply the theme to your entire app:

<application android:theme="@style/CustomActionBarTheme" ... />

Or to individual activities:

<activity android:theme="@style/CustomActionBarTheme" ... />
例如。
为了完全匹配您的使用情况,可以参考这篇Android文档文章:https://developer.android.com/training/basics/actionbar/styling.html#CustomTabs。注意使用状态列表来实现“选中样式”。

我不想在所有选项卡上应用整个主题,而是想将样式应用于单个选项卡。使用这种方法会出现警告,提示ctv未被使用。使用getActivity会出现错误,提示未定义getActivity。 - Shishi
正如我所写的,getActivity() 是从 Fragment 内部使用的,如果你在一个 Activity 中,只需使用 this。此外,看一下你添加的代码,你构造了一个 View 并将其赋值给一个变量 (ctv),但仅此而已。然后,你需要对它进行一些操作,例如将其应用为给定选项卡的视图。 - desseim
我忘记设置视图了。现在我已经设置了视图,但它仍然没有改变为我的颜色设置。 - Shishi
两件事:在您的样式xml中将@attr/actionBarTabStyle键替换为android:actionBarStyle;确保将Theme.Ab应用为应用程序或Activity的样式(而且是正确的Activity,而不是另一个)如我在答案末尾所示;现在,您至少应该看到自定义可绘制对象作为背景选项卡的背景。之后,您可以尝试为突出显示的选项卡设置特定的样式。 - desseim
@Shishi,请查看我在答案末尾添加的链接,你应该能在那里找到所需的所有内容。 - desseim
显示剩余6条评论

0

如果有其他人像我一样使用TabLayout,可以使用以下代码片段:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            tab.setCustomView(R.layout.chat_tab);

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            tab.setCustomView(null);
        }

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

        }
    });

我正在使用TabLayout,我希望第三个选项卡的文本颜色无论是否被选中都应该是红色。你能帮我吗? - Tara
我回答在下面,这将对其他人有帮助。 - Tara

0

我正在使用由AndroidStudio库提供的Tablayout。 在添加选项卡时,只需对您想要自定义的每个选项卡使用setCustomView()。就像下面这样

    tabLayout.addTab(tabLayout.newTab().setText("FirstTab"));  // default tab
    tabLayout.addTab(tabLayout.newTab().setText("SecondTab").setCustomView(R.layout.tabview));  // Customized tab

以下是特定选项卡的布局设计,这里我只是将选项卡文本颜色设置为不同的颜色

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark">  <!-- TabLayout default color in my case -->
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Procurement"
    android:textAllCaps="true"
    android:textAppearance="@android:style/TextAppearance.DeviceDefault.Small"
    android:textColor="@color/tab_selection"  <!-- textcolor which ever you like-->
    android:textStyle="bold"/>

</LinearLayout>

如果我想将颜色应用于单个选项卡,并将另一种不同的颜色应用于另一个选项卡,该怎么办? - Ananya Srivastav
我只为一个选项卡设置了颜色,你可以使用setCustomView()方法为多个选项卡设计不同的布局。你需要为每个选项卡定义不同的布局。 - Tara
你能给我一个例子作为参考吗? - Ananya Srivastav
tabLayout.addTab(tabLayout.newTab().setText("第一个标签").setCustomView(R.layout.自定义第一个标签设计)); tabLayout.addTab(tabLayout.newTab().setText("第二个标签").setCustomView(R.layout.tabview)); - Tara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接