我在一个Activity中有五个标签可以滑动。滑动选项卡工具栏文本时需要相应更改。为此,我使用接口调用从Fragment到Activity的方法,但它无法正常工作。
答案 0 :(得分:2)
我是用下面的方式做的..
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position == 0) {
toobar.setTitle("one");
} else if (position == 1) {
toobar.setTitle("two");
} else if (position == 2) {
toobar.setTitle("three");
} else if (position == 3) {
toobar.setTitle("four");
} else if (position == 4) {
toobar.setTitle("five");
}
}
答案 1 :(得分:1)
我假设您要根据所选的标签更改工具栏的标题。为此,您可以尝试使用android-support-design-library
:
示例:
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{
TabLayout tabs;
ViewPager viewPager;
TabsPagerAdapter adapter;
Toolbar toolbar;
CharSequence Titles[] = {"one", "two", "three"};
int Numboftabs = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
if (toolbar != null) {
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
}
adapter = new TabsPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
tabs.setOnTabSelectedListener(this);
tabs.setVisibility(View.GONE);
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
viewPager.setCurrentItem(0);
toolbar.setTitle("Your Title one");
break;
case 1:
viewPager.setCurrentItem(1);
toolbar.setTitle("Your Title two");
break;
case 2:
viewPager.setCurrentItem(2);
toolbar.setTitle("Your title three");
break;
default:
viewPager.setCurrentItem(tab.getPosition());
toolbar.setTitle("Your APP NAME");
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
}