我正在尝试将getString用于我的viewpager选项卡标题,以便支持多语言,但是每次我使用getString时,我都会收到错误Fragment未附加到日志中的 Activity ,并且应用程序强制关闭!

这是我的片段代码

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);


}

}

最佳答案

这是因为调用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))};
}

07-27 13:39