我从Github下载了一个代码,我无法运行该程序,问题是方法addOnPageChangeListener未定义,这是错误:
对于ViewPager类型,未定义方法addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener)
我该怎么办?我应该使用其他方法吗?这是代码:
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
public class FourthActivity extends AppCompatActivity {
// Need this to link with the Snackbar
private CoordinatorLayout mCoordinator;
//Need this to set the title of the app bar
private CollapsingToolbarLayout mCollapsingToolbarLayout;
private FloatingActionButton mFab;
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ViewPager mPager;
private YourPagerAdapter mAdapter;
private TabLayout mTabLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
mCoordinator = (CoordinatorLayout) findViewById(R.id.root_coordinator);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mAdapter = new YourPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.view_pager);
mPager.setAdapter(mAdapter);
//Notice how the Tab Layout links with the Pager Adapter
mTabLayout.setTabsFromPagerAdapter(mAdapter);
//Notice how The Tab Layout adn View Pager object are linked
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Notice how the Coordinator Layout object is used here
Snackbar.make(mCoordinator, "FAB Clicked", Snackbar.LENGTH_SHORT).setAction("DISMISS", null).show();
}
});
//Notice how the title is set on the Collapsing Toolbar Layout instead of the Toolbar
mCollapsingToolbarLayout.setTitle(getResources().getString(R.string.title_activity_fourth));
}
最佳答案
在build.gradle中找到您对android support-v4库的依赖,将版本升级到22.2.1或23.0.1,该行如下所示
compile 'com.android.support:support-v4:23.0.1'
关于android - addOnPageChangeListener未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32396846/