在视图之间滑动时,在TabLayout中更改点选择的颜色

时间:2019-05-08 07:03:12

标签: android android-tablayout

我正在使用带有点指示符的制表符布局,如下所示:

<android.support.design.widget.TabLayout
    android:id="@+id/tablayout"
    android:layout_below="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_selector"
    app:tabGravity="center"
    app:tabIndicatorHeight="0dp">

tab_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/selected_dot"
        android:state_selected="true"/>

    <item android:drawable="@drawable/default_dot"/>
</selector>

selected_dot

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:innerRadius="0dp"
            android:shape="ring"
            android:thickness="4dp"
            android:useLevel="false">
            <solid android:color="@color/colorAccent"/>
        </shape>
    </item>
</layer-list>

default_dot

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:innerRadius="0dp"
            android:shape="ring"
            android:thickness="4dp"
            android:useLevel="false">
            <solid android:color="@android:color/darker_gray"/>
        </shape>
    </item>
</layer-list>

点工作正常。

我想要做的是当我根据活动的背景更改选项卡时以编程方式更改所选点的颜色。

示例: Activity1背景白色选中的点黑色 Activity2背景黄色选定的点白色 Activity3背景红色选中的点白色

我该怎么做???我正在搜索有关此问题的几天,并尝试了很多解决方案,但对我来说都可行

我正在尝试在

上运行
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

。 。

预先感谢

MainActivity

package com.codingdemos.tablayout;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import java.lang.reflect.Field;

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;
    PageAdapter pageAdapter;
    private static final int SELECTED_COLOR = Color.GREEN;
    private static final int UNSELECTED_COLOR = Color.GRAY;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        tabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.viewPager);

        pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pageAdapter);
        viewPager.setCurrentItem(1);
        tabLayout.setupWithViewPager(viewPager, true);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                changeTabViewDotColor(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                changeTabViewDotColor(tab, false);
            }

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

            }
        });

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    }

    private void changeTabViewDotColor(TabLayout.Tab tab, boolean isSelected) {
        LayerDrawable backgroundDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.default_dot);
        GradientDrawable dotDrawable = (GradientDrawable) backgroundDrawable.findDrawableByLayerId(R.id.item_dot);
        dotDrawable.setColor(isSelected ? SELECTED_COLOR : UNSELECTED_COLOR);

        try {
            Object tabView = tab.view; //Cannot resolver symbol
            Field field = tab.getClass().getDeclaredField("baseBackgroundDrawable");
            field.setAccessible(true);
            field.set(tab, backgroundDrawable);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

        tabLayout.invalidate();
    }
}

Gradle

apply plugin: 'com.android.application'

android {
  compileSdkVersion 26
  defaultConfig {
    applicationId "com.codingdemos.tablayout"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  }
  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

dependencies {
  implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation 'com.android.support:appcompat-v7:26.1.0'
  implementation 'com.android.support.constraint:constraint-layout:1.0.2'
  implementation 'com.android.support:support-v4:26.1.0'
  testImplementation 'junit:junit:4.12'
  androidTestImplementation 'com.android.support.test:runner:1.0.1'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
  implementation 'com.android.support:design:26.1.0'
}

2 个答案:

答案 0 :(得分:0)

<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_below="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp">


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/selected_dot"
    android:state_selected="true"/>
  <item android:drawable="@drawable/default_dot"
    android:state_selected="false"/>
<item android:drawable="@drawable/default_dot"/> //you have to mention both dots here
</selector>

将此代码放入您的代码中。我注意到您没有将默认的点代码放入选择器文件中。 只需放下它并运行它就可以了。

答案 1 :(得分:0)

当前,尚无官方方法允许您在选项卡布局中更改点选择的颜色。但是有一种解决方法:

步骤1:更改gradle文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.codingdemos.tablayout"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    def support_version = '28.0.0'
    implementation "com.android.support:appcompat-v7:$support_version"
    implementation "com.android.support:support-v4:$support_version"
    implementation "com.android.support:design:$support_version"
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

步骤2:修改default_dot.xml文件

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/item_dot"> <!-- Modify this line -->
        <shape
            android:innerRadius="0dp"
            android:shape="ring"
            android:thickness="4dp"
            android:useLevel="false">
            <solid android:color="@android:color/darker_gray"/>
        </shape>
    </item>
</layer-list>

步骤3:更改MainActivity类

public class MainActivity extends AppCompatActivity {

    private static final int TAB_VIEW_SELECTED_COLOR = Color.GREEN;
    private static final int TAB_VIEW_UNSELECTED_COLOR = Color.RED;

    TabLayout tabLayout;
    ViewPager viewPager;
    PageAdapter pageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = findViewById(R.id.tablayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                changeTabViewDotColor(tab, true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                changeTabViewDotColor(tab, false);
            }

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

            }
        });

        viewPager = findViewById(R.id.viewPager);
        pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pageAdapter);
        viewPager.setCurrentItem(1);
        tabLayout.setupWithViewPager(viewPager, true);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    }

    private void changeTabViewDotColor(TabLayout.Tab tab, boolean isSelected) {
        LayerDrawable backgroundDrawable = (LayerDrawable) getResources().getDrawable(R.drawable.default_dot);
        GradientDrawable dotDrawable = (GradientDrawable) backgroundDrawable.findDrawableByLayerId(R.id.item_dot);
        dotDrawable.setColor(isSelected ? TAB_VIEW_SELECTED_COLOR : TAB_VIEW_UNSELECTED_COLOR);

        try {
            Object tabView = tab.view;
            Field field = tabView.getClass().getDeclaredField("baseBackgroundDrawable");
            field.setAccessible(true);
            field.set(tabView, backgroundDrawable);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

        tabLayout.invalidate();
    }
}

第4步::确保代码正常运行:

  • 从手机上卸载应用程序
  • 转到文件->使高速缓存无效/重新启动->使无效并重新启动
  • 运行应用