ActionBar Tabs с фрагментами (Шаблон Android Studio)
Добавлено: 03 окт 2014, 14:54
Доброго времени суток!
Всем известно Google Sample которые дают шаблоны, на использование разных элементов. И вся элементарная информация там понятно, но вот есть пару моментов, которые мне, как новичку не понять. Поскольку я не работал с выделением фрагментов на экран, так как уроки мне казались мало понятными, пока я не столкнулся с ActionBar Tabs. В одном из шаблонов таких табов надо выставить выбор фрагмента, который будет изображен в данный момент. Я написал, так сказать, от себя, что то вроде(в фрагменте кода -
public Fragment getItem(int position) {) :
Но увы, в силу слабых знаний, проект не заработал. Можно пожалуйста помочь это исправить именно в этом шаблоне, я дам код ниже. По сколько проект сделан по шаблону, на манер Google, никакой полезной информации я не нашел. Кстати, где бы я не искал информацию о Action Bar Tab везде написан громоздкий код, при чем иногда по разному на разных источниках. И кто может поделиться также информацией, по поводу табов. Что стоило бы делать, а что нет, используя табы.
Сам исходник и как это выглядит. С основу положил просто один фрагмент, который меняет цифру от секции:
Всем известно Google Sample которые дают шаблоны, на использование разных элементов. И вся элементарная информация там понятно, но вот есть пару моментов, которые мне, как новичку не понять. Поскольку я не работал с выделением фрагментов на экран, так как уроки мне казались мало понятными, пока я не столкнулся с ActionBar Tabs. В одном из шаблонов таких табов надо выставить выбор фрагмента, который будет изображен в данный момент. Я написал, так сказать, от себя, что то вроде(в фрагменте кода -
public Fragment getItem(int position) {) :
Код: Выделить всё
int pos = tab.getPosition();
if (pos == 0){
fragment = new SectionFragment1();
} else if (pos == 1){
fragment = new SectionFragment2();
} else if (pos == 2){
fragment = new SectionFragment3();
}Сам исходник и как это выглядит. С основу положил просто один фрагмент, который меняет цифру от секции:
Код: Выделить всё
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(PlaceholderFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}