As you can see in code on Google , they set TAB titles with hardcoded function.
@Override
public CharSequence getPageTitle(int position) {
return "OBJECT " (position 1);
}
But I need to use strings from XML file to make TABS dependent on localization/language. I tried this and more, but I can´t figure out, how to solve it. this is not working, because "Cannot make a static reference to the non-static method getString(int) from the type Context". Any help is appreciated.
String [] titlesArray = new String []{ getString(R.string.TAB1), getString(R.string.TAB2), getString(R.string.TAB3), getString(R.string.TAB4), getString(R.string.TAB5), getString(R.string.TAB6)};
@Override
public CharSequence getPageTitle(int position) {
return titlesArray [position];
}
Solution: Find the way how to not use STATIC context. It is possible.
CodePudding user response:
Why don't use
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.TAB1);
case 1:
return getString(R.string.TAB2);
case 2:
return getString(R.string.TAB3);
case 3:
return getString(R.string.TAB4);
case 4:
return getString(R.string.TAB5);
...AND SO ON...
}
return null;
}
}
CodePudding user response:
I think you should use Switch..Case.. block
@Override
public CharSequence getPageTitle(int position) {
Resources res = context.getResources();
switch (position) {
case 0:
return res.getString(R.string.title_section1).toUpperCase();
case 1:
return res.getString(R.string.title_section2).toUpperCase();
case 2:
return res.getString(R.string.title_section3).toUpperCase();
case 3:
return res.getString(R.string.title_section4).toUpperCase();
case 4:
return res.getString(R.string.title_section5).toUpperCase();
}
return null;
}
CodePudding user response:
I know its too late but i have found a working solution
Modify the PagerAdapter like this
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Activity activity;
static Context context;
static Resources res = null;
static String[] CONTENT = null;
public SectionsPagerAdapter(FragmentManager fm, Activity activity, Context context) {
super(fm);
this.activity = activity;
this.context = context;
res = context.getResources();
CONTENT = res.getStringArray(R.array.my_string_array);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0: {
return new PlaceHolderSignInFragment();
}
case 1: {
return new PlaceHolderSignUpFragment();
}
}
return null;
}
@Override
public int getCount() {
return SectionsPagerAdapter.CONTENT.length;
}
@Override
public CharSequence getPageTitle(int position) {
return SectionsPagerAdapter.CONTENT[position];
}
public String[] getTitles() {
return SectionsPagerAdapter.CONTENT;
}
}
In case you need for future launches!!!!