web-dev-qa-db-ja.com

個々のタブをカスタマイズする方法は? (背景色、インジケーター色、テキスト色の変更)

このリンクでは: プログラムでスタイルを適用するにはどうすればよいですか?

ケビン・グラントはこの質問に説明を与えました。彼のコードに関する私の問題はコンテキスト部分です。正確には:

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());
}

styles.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);
        }
    }

これは私が作りたいものです:

Example


ビューを使用した新しい結果については、これが起こりました

Using 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>
11
Shishi

次のように、タブの作成時にカスタムビューを設定するだけです。

_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()内。

また、上記のViewsに対応するidsをXMLレイアウトファイルに定義する必要があります(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
_

以下の情報を参照用に残しています:

このようなビューを1つ定義するには、Android Contextを指定する必要があります。これは通常、タブが表示されるActivityです。Activityでタブを初期化すると、Activityを渡すだけです。 Contextとしてのインスタンス:

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

Activity内から、または例:

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

Fragmentなどの中からの場合.

アクションバーのタブに特定のスタイルを設定する場合、プログラムでカスタムビューを作成する必要はありません。少し アクションバーについて を最初に読み、次に を確認してください。ご覧のとおり、xmlでタブスタイルを指定できます。

マニフェストファイルで、テーマをアプリ全体に適用できます。

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

または個々の活動に:

_<activity Android:theme="@style/CustomActionBarTheme" ... />
_

例えば。

ユースケースと完全に一致する完全な例については、Androidのドキュメント記事: https://developer.Android.com/training/basics/actionbar/styling.html#CustomTabs 。「選択されたときのスタイル」を実現するための状態リストの使用に注意してください。

7
desseim

私の場合のように別のものが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) {

        }
    });
0
Mostafa Anter

私は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>
0
Tara