I am trying to use getString for my viewpager tab titles so i can support multilanguages, but every time i use getString i get the error Fragment not attached to activity in the logs and the app Force Closes!
Here is my fragment code
public class RecipesFragment extends Fragment {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence[] Titles = {(getResources().getString(R.string.invcraftingcardtitle)), (getResources().getString(R.string.wbcraftingcardtitle)), (getResources().getString(R.string.ovencraftingcardtitle)), (getResources().getString(R.string.painttitle))};
int Numboftabs = 4;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.recipes_fragment, container, false);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager(), Titles, Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) getView().findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) getView().findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
}
This is because your variable Titles
as getResources
can be used after onAttach
is called
try to initialize it in onAttach
method like this:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Titles = {(getResources().getString(R.string.invcraftingcardtitle)), (getResources().getString(R.string.wbcraftingcardtitle)), (getResources().getString(R.string.ovencraftingcardtitle)), (getResources().getString(R.string.painttitle))};
}
The issue is that getResources()
actually calls getActivity().getResources()
and you are using it in variable initiation (before being attached to the activity). Try setting up the titles variable right before you need to use it.
I would also avoid having variables start with an uppercase letter as this makes them seem as though they are classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.