无法解析方法'addOnTabSelectedListener(anonymous android.support.design.widget.TabLayout.OnTabSelectedListener)'

时间:2016-11-16 12:04:32

标签: android android-viewpager android-tablayout

我不知道为什么,但我无法使用addOnTabSelectedListener,虽然我可以使用setOnTabSelectedListener(),但我不想这样做。这是我的代码:

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

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    back = (ImageView) findViewById(R.id.back_navigation);
    fab = (FloatingActionButton) findViewById(R.id.fab_explore);
    viewPager = (CustomViewPager) findViewById(R.id.viewPager_home);
    tabLayout = (TabLayout) findViewById(R.id.bottom_navigation2);
    navigationView = (NavigationView) findViewById(R.id.nav_view);

    DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) navigationView.getLayoutParams();
    params.width = (int) (width * 0.9);
    navigationView.setLayoutParams(params);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            drawer.openDrawer(GravityCompat.START);
        }
    });
    setupViewPager(viewPager);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            drawer.closeDrawer(GravityCompat.START);
        }
    });
    tabLayout.setupWithViewPager(viewPager);
    setupIcon();
    tabLayout.getTabAt(0).getIcon().setAlpha(255);
    tabLayout.getTabAt(1).getIcon().setAlpha(100);
    tabLayout.getTabAt(2).getIcon().setAlpha(100);
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

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

        }
    });
}

public void setupIcon() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Digest(), "Digest");
    adapter.addFragment(new Topics(), "Topics");
    adapter.addFragment(new Profile(), "Profile");
    viewPager.setAdapter(adapter);
}

我不知道我做错了什么。我的compileSdkVersion是23,所有的android支持库也是23。

2 个答案:

答案 0 :(得分:1)

在build.gradle文件中添加依赖项

dependencies {
compile 'com.android.support:design:23.1.1'
}

答案 1 :(得分:1)

确保您的构建版本和设计支持库版本相同。在您的情况下,构建工具版本和您的设计支持库版本不同,所以您面临的问题

例如在我的情况下:

compileSdkVersion 25
buildToolsVersion '25.0.0'

和依赖

compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'

并且该错误肯定会消失。