10

В этой ссылке: How do I apply a style programmatically?Как настроить отдельные вкладки? (Изменение цвета фона, цвета индикатора и цвета текста)

Кевин Грант дал объяснения на этот вопрос моей проблему с его кодом является контекст частью. Чтобы быть точными:

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> 
+0

ли это в пределах деятельности? Попробуйте использовать это вместо контекста (который, кажется, является экземпляром, который вы еще не объявили) – nKn

+0

Да, это в FragmentActivity, который реализует ActionBar.TabListener, используя это, разрешает ошибку, но не применяет мой стиль к моей вкладке – Shishi

+0

Затем вам нужно будет вызвать getActivity() вместо контекста. Я рекомендую прочитать ответ @ desseim, поскольку вам это может показаться интересным. – nKn

ответ

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().

Вы также должны определить View s соответствующие указанным выше id с в файле макета XML (а не style s).

Или, если вы хотите создать представление непосредственно:

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, и т. д.

Что касается установки определенного стиля вкладок панели действий, нет необходимости идти, создавая пользовательский вид программно, как вы пытаетесь сделать. Сначала прочитайте немного about the action bar, затем проверьте the example, которые они предоставляют. Как вы можете видеть, вы будете в состоянии указать вкладку стиль в XML:

В вашем файле манифеста, вы можете применить тему ко всему приложение:

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

Или в отдельных видов деятельности :

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

, например.

Полный текст примера, подходящего для вашего использования, см. В этой статье документа для Android: https://developer.android.com/training/basics/actionbar/styling.html#CustomTabs. Обратите внимание на использование государственных списков для достижения «при выборе стиля».

+0

Я не пытаюсь использовать целую тему, как это применимо ко всем вкладкам. Я хочу применить стиль к отдельной вкладке. Используя это, вы предупреждаете, что ctv не используется. using getActivity дает ошибку, говоря, что getActivity не определено – Shishi

+0

Как я писал 'getActivity()' используется изнутри 'Fragment', если вы находитесь в' Activity', просто используйте 'this'. Кроме того, глядя на добавленный код, вы создаете 'View' и влияете на него на переменную (' ctv'), но это все. Затем вам нужно что-то сделать с ним, например, применить его как представление для данной вкладки. – desseim

+0

Я забыл установить представление действительно. Теперь, когда я установил представление, он по-прежнему не меняет его на мои настройки цвета. – Shishi

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) { 

     } 
    }); 
+0

Я использую tabLayout и Я хочу, чтобы цвет текста третьей вкладки должен быть красного цвета независимо от выбора/нет. Можете ли вы мне помочь? – Tara

+0

Я ответил ниже, это будет полезно для других. – Tara

+0

хорошая работа Тара. –

0

Я использую Tablayout, который privided библиотекой AndroidStudio. при добавлении вкладок Просто используйте setCustomView() для каждой вкладки, которую вы хотите настроить. что-то вроде ниже

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

и ниже является дизайн-макет для конкретной вкладки, чтобы заполнить наше требование, здесь я только она позволяет цвет текста Tab Different

<?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

Что делать, если я хочу применить цвет к одной вкладке и другой цвет к другой вкладке –

+0

Я дал цвет только одной вкладке с помощью setCustomView(), которую вы можете создать для количества вкладок. Вы должны определить разные макеты для разных вкладок. – Tara

+0

Можете ли вы привести мне пример ссылки –

Смежные вопросы