Access to getString() in android.support.v4.app.FragmentPagerAdapter?

蹲街弑〆低调 提交于 2019-11-28 00:24:01

问题


In a class extending android.support.v4.app.FragmentPagerAdapter, is there any way to get access to the Context.getString(..) method without the extending class being an inner class of an activity or passing in some context from the outside?

Thanks for any hint!


回答1:


From a fragment use :

 getActivity().getString(...)

From an adapter use :

 getContext().getResources().getString(...)

Yes, you need a context to access the resources.




回答2:


From an Activity, use:

this.getString(R.string.string_name);

From a Fragment, use:

getActivity.getString(R.string.string_name);

From an adapter, use:

getContext().getResources().getString(R.string.string_name);



回答3:


I had a similar issue. From a drawer layout, I wanted to decide which fragment to use in a method called from a helper class.

So in onCreateView...

String form = getResources().getStringArray(R.array.drawer_array)[i];
        Context context = getActivity().getApplicationContext();

        FragmentHelper fh = new FragmentHelper();
        int myFragment = fh.getCurrentFragment(form,context);

And in public FragmentHelper()...

    public int getCurrentFragment(String form, Context context){
              ...
              context.getResources().getString(R.string.label_item1);
              ...
    }

The trick being to add context in front of getResources(). Otherwise, my stack showed that the fragment was not attached to an activity.

Hope this helps someone.



来源:https://stackoverflow.com/questions/14112628/access-to-getstring-in-android-support-v4-app-fragmentpageradapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!