我正在尝试使用getString作为我的viewpager选项卡标题,所以我可以支持多语言,但每次我使用getString我得到错误片段没有附加到日志中的活动和应用程序强制关闭!
这是我的片段代码
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);
}
}
答案 0 :(得分:5)
这是因为在调用Titles
后可以使用getResources
作为onAttach
的变量
尝试在onAttach
方法中初始化它,如下所示:
@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))};
}
答案 1 :(得分:0)
问题是getResources()
实际上调用getActivity().getResources()
并且您在变量启动中使用它(在附加到活动之前)。尝试在需要使用之前设置titles变量。
我也会避免让变量以大写字母开头,因为这会使它们看起来好像是类。