TabLayout에서 선택한 탭의 아이콘 색상을 어떻게 변경합니까?
a TabLayout
와 함께 사용하고 있으며 ViewPager
TabLayout에서 선택한 탭의 아이콘 색상을 가장 효율적으로 변경할 수있는 방법이 궁금합니다.
이것이 어떻게 구현되는지에 대한 완벽한 참조는 Google의 Youtube 앱 입니다. 메인 페이지에는 짙은 회색으로 표시된 4 개의 아이콘이 있습니다. 특정 탭을 선택하면 탭 아이콘이 흰색으로 바뀝니다.
타사 라이브러리없이 어떻게 동일한 효과를 얻을 수 있습니까?
한 가지 가능한 해결책은 분명히 선택자를 사용하는 것입니다. 그러나이 경우 흰색과 회색 버전의 아이콘을 모두 찾은 다음 탭이 선택되거나 선택 취소되면 아이콘을 전환해야합니다. 아이콘 색상 등 만 강조 표시 할 수있는 더 효과적인 방법이 있는지 궁금합니다. 나는 어떤 튜토리얼에서도 이것을 찾을 수 없었습니다.
편집하다
위에서 직접 언급 한 솔루션은 각 탭의 아이콘에 대해 두 개의 드로어 블을 사용해야합니다. 각 탭의 아이콘에 대해 하나의 드로어 블을 사용 하여 프로그래밍 방식으로 수행 할 수있는 방법이 있는지 궁금 합니다.
쉬운 방법을 찾았습니다.
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
int tabIconColor = ContextCompat.getColor(context, R.color.tabSelectedIconColor);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
super.onTabUnselected(tab);
int tabIconColor = ContextCompat.getColor(context, R.color.tabUnselectedIconColor);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
super.onTabReselected(tab);
}
}
);
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(0).getIcon().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(1).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(2).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(3).getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
ColorStateList를 사용할 수 있습니다.
먼저 /color/tab_icon.xml
다음과 같은 xml 파일 (예 :)을 만들고 서로 다른 상태에 대해 서로 다른 색조를 정의합니다.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/icon_light"
android:state_selected="true" />
<item android:color="@color/icon_light_inactive" />
</selector>
그런 다음 코드에 다음을 추가하십시오.
ColorStateList colors;
if (Build.VERSION.SDK_INT >= 23) {
colors = getResources().getColorStateList(R.color.tab_icon, getTheme());
}
else {
colors = getResources().getColorStateList(R.color.tab_icon);
}
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
Drawable icon = tab.getIcon();
if (icon != null) {
icon = DrawableCompat.wrap(icon);
DrawableCompat.setTintList(icon, colors);
}
}
먼저 XML에서 ColorStateList를 가져옵니다 (테마가없는 메서드는 더 이상 사용되지 않지만 Marshmallow 이전 장치에 필요함). 그런 다음 각 탭의 아이콘에 대해 TintList를 ColorStateList로 설정합니다. DrawableCompat (지원 라이브러리)를 사용하여 이전 버전도 지원합니다.
그게 다야!
이것은 매우 간단하게 전적으로 xml로 수행 할 수 있습니다.
app:tabIconTint="@color/your_color_selector"
아래와 같이 xml의 TabLayout에 한 줄을 추가 합니다.
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIconTint="@color/your_color_selector"
app:tabIndicatorColor="@color/selected_color"/>
그런 다음 res / color 디렉토리에 색상 선택기 파일 (위의 "your_color_selector.xml")을 만듭니다.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/selected_color" android:state_selected="true"/>
<item android:color="@color/unselected_color"/>
</selector>
colors.xml 파일에 "selected_color"및 "unselected_color"의 두 가지 색상이 있다고 가정합니다.
이를 위해 다음과 같이 각 탭에 대한 선택기 클래스를 사용하여 탭 아이콘을 사용자 정의해야합니다.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/advisory_selected" android:state_selected="true" />
<item android:drawable="@drawable/advisory_normal" android:state_selected="false" />
다음 코드를 확인하십시오. 아이콘 하나는 색상이고 다른 하나는 색상이 아닙니다.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/mybookings_select" android:state_selected="true"/><!-- tab is selected(colored icon)-->
<item android:drawable="@drawable/mybookings" /><!-- tab is not selected(normal no color icon)-->
아이콘에 아이콘 글꼴 (예 : 멋진 글꼴)을 사용하지 않는 이유는 무엇입니까? 그런 다음 탭 텍스트의 글꼴을 원하는 글꼴 아이콘 .ttf로 변경하고 선택한 텍스트 색상을 탭 아이콘으로 변경하십시오!
나 자신이이 방법을 사용했는데 정말 멋지고 깨끗합니다. :)
먼저 원하는 아이콘 글꼴에서 제목을 설정합니다.
string.xml에서 :
<string name="ic_calculator"></string>
<string name="ic_bank"></string>
그런 다음 MainActivity.Java에서 :
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentBank(), getString(R.string.ic_bank));
adapter.addFragment(new FragmentCalculate(), getString(R.string.ic_calculator));
viewPager.setAdapter(adapter);
}
그런 다음 탭 제목의 글꼴을 font-awesome으로 변경해야합니다.
Typeface typeFaceFont = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(typeFaceFont);
}
}
}
마지막으로 관련 .xml 파일에서 tabTextColor 및 tabSelectedTextColor에 대한 색상을 설정합니다.
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="horizontal"
android:background="@color/colorPrimaryDark"
app:tabSelectedTextColor="@color/colorAccent"
app:tabTextColor="@color/textColorPrimary"
app:tabIndicatorColor="@color/colorAccent"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
그리고 colors.xml에서 :
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="colorHighlight">#FFFFFF</color>
<color name="textColorPrimary">#E1E3F3</color>
</resources>
색상을 별도로 설정하는 방법을 보여주는 두 번째 답변을 참조하면 많은 사람들이 다음 아이콘으로 전환하면서 첫 번째 아이콘의 색상을 제거하는 방법에 대해 궁금해 할 것입니다. 당신이 할 수있는 일은 다음과 같이하는 것입니다.
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(0).getIcon().setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(1).getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(2).getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
tabLayout.getTabAt(3).getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.GREEN,PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
//for removing the color of first icon when switched to next tab
tablayout.getTabAt(0).getIcon().clearColorFilter();
//for other tabs
tab.getIcon().clearColorFilter();
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});}
나는 두 번째 답변에 대해 언급했을 것이지만 그것에 대한 평판이 충분하지 않았습니다! 죄송합니다. 그러나 시간과 두통을 절약 할 수 있다는 것을 따르십시오! 행복한 학습
res > colors
디렉토리 아래에 추가하십시오 .
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="@android:color/holo_orange_dark"/>
<item android:color="@android:color/holo_red_light"/>
</selector>
xml의 탭보기에 코드를 추가합니다.
app:tabIconTint="@color/selector_tab"
아이콘을 "강조 표시"하는 한 가지 가능한 방법은 이미지보기에 액세스하고 컬러 필터를 설정하는 것입니다. setColorFilter (int color) ImageView 메서드를 사용하고 흰색을 적용 해보십시오.
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {...}
더 이상 사용되지 않습니다. 오히려 사용
tabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int tabIconColor = ContextCompat.getColor(context, R.color.tabSelectedIconColor);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
int tabIconColor = ContextCompat.getColor(context, R.color.tabUnselectedIconColor);
tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
다음 코드를 확인하십시오.
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(tab.getPosition() == 0){
tabLayout.getTabAt(0).setIcon(tabIcons1[0]);
}
if(tab.getPosition() == 1){
tabLayout.getTabAt(1).setIcon(tabIcons1[1]);
}
if(tab.getPosition() == 2){
tabLayout.getTabAt(2).setIcon(tabIcons1[2]);
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
을 (를) 사용할 수 있습니다 addOnTabSelectedListener
.
tablayout = findViewById(R.id.viewall_tablayout);
pager = findViewById(R.id.viewall_pager);
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragments(new RestFragment(),"Restaurant");
adapter.addFragments(new BarFragment(),"Bar");
adapter.addFragments(new HotelFragment(),"Hotel");
adapter.addFragments(new CoffeeFragment(),"Coffee Shop");
pager.setAdapter(adapter);
tablayout.setupWithViewPager(pager);
tablayout.getTabAt(0).setIcon(R.drawable.ic_restaurant);
tablayout.getTabAt(1).setIcon(R.drawable.ic_glass_and_bottle_of_wine);
tablayout.getTabAt(2).setIcon(R.drawable.ic_hotel_black_24dp);
tablayout.getTabAt(3).setIcon(R.drawable.ic_hot_coffee);
tablayout.getTabAt(0).getIcon().setTint(getResources().getColor(R.color.colorAccent,getTheme()));
tablayout.getTabAt(1).getIcon().setTint(getResources().getColor(R.color.colorAccent,getTheme()));
tablayout.getTabAt(2).getIcon().setTint(getResources().getColor(R.color.colorAccent,getTheme()));
tablayout.getTabAt(3).getIcon().setTint(getResources().getColor(R.color.colorAccent,getTheme()));
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setTint(getResources().getColor(R.color.colorPrimary,getTheme()));
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setTint(getResources().getColor(R.color.colorAccent,getTheme()));
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
여기 에서 ColorStateList로 선호하는 답변을 확장 하면 사용자 정의 탭을 사용하는 경우 다음 솔루션을 사용할 수 있습니다.
활동의 xml에 탭 설정
...
<android.support.design.widget.TabLayout
android:id="@+id/main_tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabItem
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/nav_bar_tab_item"/>
<android.support.design.widget.TabItem
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout="@layout/nav_bar_tab_item"/>
</android.support.design.widget.TabLayout>
...
그리고 사용자 정의 탭 레이아웃 nav_bar_item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="@+id/nav_bar_item_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingEnd="@dimen/_5sdp"
android:paddingStart="@dimen/_5sdp">
<ImageView
android:id="@+id/item_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="@+id/item_description"
android:layout_width="wrap_content"
android:gravity="center"
<!-- Use selector here to change the text color when selected/unselected -->
android:textColor="@color/nav_bar_icons_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/item_img"/>
</android.support.constraint.ConstraintLayout>
당신의 활동에서
tabLayout = findViewById(R.id.main_tablayout);
ConstraintLayout navMyHotelLayout = (ConstraintLayout) tabLayout.getTabAt(0)
.getCustomView();
tab1Icon = navMyHotelLayout.findViewById(R.id.item_img);
tab1TextView = navMyHotelLayout.findViewById(R.id.item_description);
tab1Icon.setImageResource(R.drawable.ic_tab1);
// Use the selector here to change the color when selected/unselected
tintImageViewSelector(tab1Icon, R.color.nav_bar_icons_color);
tab1TextView.setText("tab 1");
ConstraintLayout navTtdLayout = (ConstraintLayout) tabLayout.getTabAt(1)
.getCustomView();
tab2Icon = navTtdLayout.findViewById(R.id.item_img);
tab2View = navTtdLayout.findViewById(R.id.item_description);
tab2Icon.setImageResource(R.drawable.ic_tab2);
tintImageViewSelector(tab2Icon, R.color.nav_bar_icons_color);
tab2TextView.setText("tab 2");
And add these helper functions for the change of color
public static void tintDrawableSelector(Drawable vd, final @ColorRes int clrRes, Context context) {
DrawableCompat.setTintList(vd, ContextCompat.getColorStateList(context, clrRes));
}
public static void tintImageViewSelector(ImageView imgView, final @ColorRes int clrRes, Context context) {
tintDrawableSelector(imgView.getDrawable(), clrRes);
}
Finally, the selector nav_bar_icons_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@android:color/white" android:state_checked="true"/>
<item android:color="@android:color/white" android:state_selected="true"/>
<item android:color="@android:color/black"/>
</selector>
You can change the text color of selected tab using the following xml attribute of Tab layout :
app:tabSelectedTextColor="your desired color"
To customize your icon color of selected tab you need to use selector Create a xml file under drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="selected_item_color" android:state_activated="true" />
<item android:color="unselected_item_color" />
</selector>
and add this selector to tab layout xml attribute like below:
app:tabIconTint="@drawable/name_of_file"
Perform the following steps respectively.
app/src/main/res/values/colors.xml (Add to colors.xml)
<color name="icon_enabled">#F3D65F</color>
<color name="icon_disabled">#FFFFFF</color>
app/src/main/res/color/custom_tab_icon.xml (Create a folder named color in res. Create a custom tab icon.xml in the folder.)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/icon_enabled" android:state_selected="true"/>
<item android:color="@color/icon_disabled" android:state_selected="false"/>
</selector>
app/src/main/res/drawable/ic_action_settings.png (Create)
double click on action_settings to add
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="21.6"
android:viewportHeight="21.6"
android:tint="@color/custom_tab_icon">
<group android:translateX="-1.2"
android:translateY="-1.2">
<path
android:fillColor="#FF000000"
android:pathData="M19.1,12.9a2.8,2.8 0,0 0,0.1 -0.9,2.8 2.8,0 0,0 -0.1,-0.9l2.1,-1.6a0.7,0.7 0,0 0,0.1 -0.6L19.4,5.5a0.7,0.7 0,0 0,-0.6 -0.2l-2.4,1a6.5,6.5 0,0 0,-1.6 -0.9l-0.4,-2.6a0.5,0.5 0,0 0,-0.5 -0.4H10.1a0.5,0.5 0,0 0,-0.5 0.4L9.3,5.4a5.6,5.6 0,0 0,-1.7 0.9l-2.4,-1a0.4,0.4 0,0 0,-0.5 0.2l-2,3.4c-0.1,0.2 0,0.4 0.2,0.6l2,1.6a2.8,2.8 0,0 0,-0.1 0.9,2.8 2.8,0 0,0 0.1,0.9L2.8,14.5a0.7,0.7 0,0 0,-0.1 0.6l1.9,3.4a0.7,0.7 0,0 0,0.6 0.2l2.4,-1a6.5,6.5 0,0 0,1.6 0.9l0.4,2.6a0.5,0.5 0,0 0,0.5 0.4h3.8a0.5,0.5 0,0 0,0.5 -0.4l0.3,-2.6a5.6,5.6 0,0 0,1.7 -0.9l2.4,1a0.4,0.4 0,0 0,0.5 -0.2l2,-3.4c0.1,-0.2 0,-0.4 -0.2,-0.6ZM12,15.6A3.6,3.6 0,1 1,15.6 12,3.6 3.6,0 0,1 12,15.6Z"/>
</group>
</vector>
'programing' 카테고리의 다른 글
Google C ++ 테스트 프레임 워크에서 사용자 지정 메시지를 보내는 방법은 무엇입니까? (0) | 2020.11.19 |
---|---|
iOS 7 : "레이블-레이블"에 대한 잘못 배치 된 뷰 프레임이 런타임에 달라짐 (0) | 2020.11.19 |
ctrl + shift + f를 사용하여 VSCode에서 선택한 코드를 들여 쓰거나 서식을 지정하는 방법 (0) | 2020.11.19 |
MySQL과 Postgres 모두에 대해 대소 문자를 구분하지 않는 쿼리를 어떻게 작성합니까? (0) | 2020.11.19 |
270921sec를 일 + 시간 + 분 + 초로 변환하는 방법? (0) | 2020.11.19 |