我已尝试使用ViewPager和slidingtablayout跟踪指南,但它们似乎不起作用或已弃用。现在,在Android模板上创建标签的实际最佳方法是什么?
或者有人可以通过简单明了的解释向我指导指南/教程吗?
答案 0 :(得分:0)
使用专为此目的而创建的库,可以非常轻松地创建选项卡:
将依赖性添加到应用程序(非项目)build.gradle:
dependencies {
compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
}
在您的布局(XML)中包含一个PagerSlidingTabStrip小部件,通常位于它所代表的ViewPager
之上:
<com.astuetz.PagerSlidingTabStrip
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
创建一个ViewPager适配器:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* TabsPagerAdapter.
*
* @author Niels
* @version 1.0
* @since 11-9-2015
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
/**
* Contains all the fragments.
*/
private List<Fragment> fragments = new ArrayList<>();
/**
* Contains all the tab titles.
*/
private List<String> tabTitles = new ArrayList<>();
/**
* Creates a new PagerAdapter instance.
*
* @param fragmentManager The FragmentManager.
*/
public TabsPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}
/**
* Adds the fragment to the list, also adds the fragment's tab title.
*
* @param fragment New instance of the Fragment to be associated with this tab.
* @param tabTitle A String containing the tab title for this Fragment.
*/
public void addFragment(Fragment fragment, String tabTitle) {
fragments.add(fragment);
tabTitles.add(tabTitle);
}
}
最后,在你的活动中onCreate:
//adapter = view.findViewById(...)
//viewpager = view.findViewById(...)
adapter = new TabsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentTab1() "Tab 1");
adapter.addFragment(new FragmentTab2(), "Tab 2");
adapter.addFragment(new FragmentTab3(), "Tab 3");
adapter.addFragment(new FragmentTab4(), "Tab 4");
viewpager.setAdapter(adapter);
strip.setViewPager(viewpager);