How can I convert the android resources int to a string. eg.: android.R.string.cancel?

三世轮回 提交于 2019-11-29 10:56:54

问题


How can I obtain the string value "cancel" from this resource int: android.R.string.cancel ?

thank you


回答1:


Simply use Context#getString():

String string = getString(android.R.string.cancel);

I've already tried this approach but with no success... I've a class: public class MyDialogFragment extends DialogFragment {

A DialogFragment is not a subclass of Context, so you need to get access to a valid one (like your Activity's). Use this:

String string = getActivity().getString(android.R.string.cancel);

Or as your discovered you can use the Activity passed in onAttach(), but understand you can do this anywhere inside a Fragment as long as you have a valid Context to work with.




回答2:


As indicated here: http://developer.android.com/reference/android/content/Context.html#getString(int)

String s = context.getString(android.R.string.cancel);

context can be the current activity, or any object inheriting the Context abstract class.




回答3:


This will convert any Android resource into a string. In this example I’ve used an ‘R.color.myColor’ but it will work with any Android resource type.

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="btnDialBgColor">#00BFA5</color>
    <color name="btnDialBgColorActive">#C51162</color>
</resources>

TypedValue typedValueActive = new TypedValue();
TypedValue typedValue = new TypedValue();
getResources().getValue(R.color.btnDialBgColorActive, typedValueActive, true);
getResources().getValue(R.color.btnDialBgColor, typedValue, true);

Hope this helps.



来源:https://stackoverflow.com/questions/13388493/how-can-i-convert-the-android-resources-int-to-a-string-eg-android-r-string-c

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