Android 如何从资源 id 中获取资源名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10137692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Resource Name from Resource id
提问by Code_Life
In my layout I have defined something like this .
在我的布局中,我定义了这样的东西。
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
Assume that some function in activity returns me this id (id of radioButton). Now i want to get this text radio1from this id.
In short I want to retrieve text radio1written in android:id="@+id/radio1"
假设活动中的某个函数向我返回这个 id(radioButton 的 id)。现在我想从这个 id获取这个文本radio1。简而言之,我想检索写在的文本radio1android:id="@+id/radio1"
Can somebody tell me how is it possible ?
有人能告诉我怎么可能吗?
回答by Shubhayu
In your Activity, try these:
在你的活动中,试试这些:
to get string like
radio1
:getResources().getResourceEntryName(int resid);
to get string like
com.sample.app:id/radio1
:getResources().getResourceName(int resid);
得到像这样的字符串
radio1
:getResources().getResourceEntryName(int resid);
得到像这样的字符串
com.sample.app:id/radio1
:getResources().getResourceName(int resid);
In Kotlin Now :
现在在 Kotlin 中:
val name = v.context.resources.getResourceEntryName(v.id)
回答by Anil Jadhav
You have id('long' type)from that id you want to access radio button id(name)that is radio1. You use this
你有id('long' type)来自你想要访问单选按钮id(name) 的那个id是radio1。你用这个
getResources().getResourceEntryName(id);
in using above you can get name of radio button i.e. radio1. here parameter id is which you have(long type). Try this it will helps you 100%.
在使用上面你可以获得单选按钮的名称,即radio1。这里的参数 id 是您拥有的 (long type)。试试这个它会帮助你 100%。
回答by Anand Makwana
Kotlin:
科特林:
val name = v.context.resources.getResourceEntryName(v.id)
回答by Anand Makwana
If I am right, what you wanted to retrieve is the word "radio1" (from the id itself?) so if that's the case then first you need to get its id.
如果我是对的,您想要检索的是单词“radio1”(来自 id 本身?)所以如果是这种情况,那么首先您需要获取它的 id。
int intname= buttonname.getId();
then get the result of it
然后得到它的结果
String stringname= getResources().getResourceEntryName(intname);
hoped I helped
希望我有所帮助
回答by Dimitris Makris
You mean you want to take the string text of the id?
你的意思是你想取id的字符串文本?
Since you have defined it you should know what this is.
既然你已经定义了它,你应该知道这是什么。
If you have a layout and you want to find if a View has a specific id, you can traverse the whole layout and check with getId(), if the id of each View is the id you are looking for..
如果你有一个布局并且你想找到一个视图是否有特定的 id,你可以遍历整个布局并使用 getId() 检查,如果每个视图的 id 是你要查找的 id..
Hope this helps (if I have understand correct your question.. :) )
希望这会有所帮助(如果我理解正确您的问题.. :))