Comment personnaliser les onglets? (changer la couleur d'arrière-plan, l'indicateur de couleur et la couleur du texte)
Dans ce lien : Comment puis-je appliquer un style par programmation?
Kevin Grant a donné une explication à cette question, mon problème avec son code est le contexte de la partie. Pour être plus précis :
ctv = new CustomView(context, R.attr.tabStyleAttr);
Dans ce code, il dit : contexte ne peut pas être résolu à une variable
Je veux appliquer le style spécifique à onglets et c'est pourquoi le thème ne fonctionne pas pour moi. Une alternative à mon problème est le bienvenu bien sûr.
J'ai essayer de changer la couleur de fond, la couleur du témoin lumineux et la couleur du texte de l'actionbar onglets.
@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);
}
}
C'est ce que je veux faire:
Comme pour le nouveau résultat à l'aide de Vues de ce qui s'est passé
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>
Oui, c'est dans un FragmentActivity qui implémente l'ActionBar.TabListener à l'aide de ce fait résoudre l'erreur, mais il ne s'applique pas à mon style de mon onglet
Ensuite, vous aurez à appeler getActivity() à la place de contexte. Je recommande la lecture de @desseim de la réponse que vous pourriez trouver intéressant.
Je veux donner à chaque onglet de couleur différente et de l'onglet sélectionné un autre textcolor. Comme pour le témoin, je voudrais une ligne de la même couleur que la couleur de l'onglet sélectionné. (la ligne doit aller sous tous les onglets comme avec la racine des cheveux dans l'actionbar générateur)
Il sera plus facile de vous aider si vous aussi, vous collez le code où vous initialisez vos onglets et la barre d'onglet.
OriginalL'auteur Shishi | 2014-01-24
Vous devez vous connecter pour publier un commentaire.
Il suffit de régler votre affichage personnalisé à la création d'un onglet de temps, quelque chose comme:
dans
inCreate()
.Vous aurez également à définir
View
s correspondant à la ci-dessusid
s dans votre xml fichier de mise en page (et passtyle
s).Ou, si vous voulez créer la vue directement:
En laissant les informations ci-dessous pour référence:
De définir l'un de ces points de vue, vous devez le spécifier un Android
Context
. C'est généralement leActivity
où les onglets sont affichés.En supposant que vous initialisez vos onglets dans un
Activity
, il suffit de passer leActivity
instance comme unContext
:si, à partir de l'intérieur de la
Activity
, ou par exemple:si, à partir de l'intérieur d'un
Fragment
, etc.Que pour la création d'un style spécifique pour l'action de la barre des onglets, pas besoin d'aller créer une vue personnalisée par programme que vous essayez de. Lisez un peu sur la barre d'action d'abord, puis de vérifier l'exemple qu'ils fournissent. Comme vous pouvez le voir, vous serez en mesure de préciser le style d'onglet dans le fichier xml:
par exemple.
Pour un exemple complet correspondant parfaitement à votre cas d'utilisation, voir ce Android doc de l'article: https://developer.android.com/training/basics/actionbar/styling.html#CustomTabs . Remarquez l'utilisation de l'état des listes d'atteindre le "quand style sélectionné".
Comme je l'ai écrit
getActivity()
est utilisé à partir de l'intérieur d'unFragment
, si vous êtes dans uneActivity
suffit d'utiliserthis
. En outre, en regardant le code que vous avez ajouté, vous construisez unView
et de l'affecter à une variable (ctv
), mais c'est tout. Vous avez besoin de faire quelque chose avec elle, puis, par exemple de l'appliquer comme la vue d'un onglet.J'ai oublié de définir le point de vue en effet. Maintenant que j'ai défini la vue, il ne change toujours pas à mes paramètres de couleur.
2 choses: remplacer
@attr/actionBarTabStyle
clé avecandroid:actionBarStyle
dans vos styles xml ; assurez-vous que vous appliquezTheme.Ab
comme un style de l'app ou de l'Activity
(et le droitActivity
, et pas un autre) que je l'ai souligné à la fin de ma réponse ; maintenant, vous devriez voir au moins personnalisé un drawable comme toile de fond de fond des onglets. Après cela, vous pouvez essayer de définir un style pour en surbrillance onglets.voir le lien que j'ai ajouté à la fin de ma réponse trop, vous devriez trouver tout ce dont vous avez besoin.
OriginalL'auteur desseim
si un autre à l'aide de TabLayout comme dans mon cas, j'ai utilisé cet extrait
J'ai répondu ci-dessous, il sera utile pour les autres.
bon travail de Tara .
OriginalL'auteur Mostafa Anter
J'ai été en utilisant Tablayout, qui est privided par AndroidStudio de la bibliothèque.
lors de l'ajout des onglets utilisation setCustomView() pour chaque onglet qui vous souhaitez personnaliser. quelque chose comme ci-dessous
Et ci-dessous le plan de la conception pour les Onglet en particulier pour combler nos besoins, je suis Ici juste makeing l'Onglet couleur de texte Différente
j'ai donné de la couleur à un seul onglet avec setCustomView(), vous pouvez concevoir pour le nombre d'onglets. Vous devez définir des mises en page différentes pour les différents onglets.
Pouvez-vous me donner un exemple comme référence
tabLayout.addTab(tabLayout.newTab().setText("FirstTab").setcustomview(R. layout.customDesignForfirsttab)); tabLayout.addTab(tabLayout.newTab().setText("SecondTab").setCustomView(R. layout.tabview));
OriginalL'auteur Tara