gpt4 book ai didi

android - 如何使用 ViewPager.OnPageChangeListener

转载 作者:行者123 更新时间:2023-11-29 14:26:29 24 4
gpt4 key购买 nike

根据 this接受的答案,我能够得到我的 tabLyout 如下:

enter image description here

我现在需要的是能够根据 fragment 位置更改按钮文本,例如,如果位置为零,则不应出现 Back,如果位置为最后,Next 应该替换为 Done

我使用了 ViewPager.OnPageChangeListener 但对我不起作用,下面是完整代码:

public class Slider extends AppCompatActivity {

private TabLayout tabLayout;
private ViewPager viewPager;
private Button leftBtn, rightBtn;

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

leftBtn = (Button) findViewById(R.id.left_btn);
rightBtn= (Button) findViewById(R.id.right_btn);

viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);

tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}

// This is not working, even the `Toast` not appearing
private ViewPager.OnPageChangeListener listener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
Toast.makeText(Slider.this, "Current position: "+position, Toast.LENGTH_SHORT).show();
if (position == 0) {
leftBtn.setText("");
}

if (position == 3) {
rightBtn.setText("DONE");
}
}

@Override
public void onPageScrollStateChanged(int state) {

}
};

private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Tab1(),"");
adapter.addFrag(new Tab2(),"");
adapter.addFrag(new Tab3(),"");
adapter.addFrag(new Tab4(),"");
viewPager.setAdapter(adapter);
}

static class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}

@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}

@Override
public int getCount() {
return mFragmentList.size();
}

public void addFrag(Fragment fragment, String title) {

mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}

public void next_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
}

public void previous_fragment(View view) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1);
}

public void start_app(View view) {
startActivity(new Intent(Slider.this, TrustedNumber.class));
finish();
}
}

最佳答案

是因为你没有给viewpager加监听

viewPager.addOnPageChangeListener(listener);

关于android - 如何使用 ViewPager.OnPageChangeListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43675161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com