更简单的方法来获得视图的ID(字符串)通过其ID(INT) [英] Easier way to get view's Id (string) by its Id (int)
问题描述
我是新与Android和Java,很抱歉,如果这是一个太简单的问题,但我一直在努力,发现在论坛上的解决方案和谷歌,我不能。
I'm new with android and java, so sorry if it's a too basic question but I've tried to find a solution in the forums and google and I couldn't.
我在我的布局的24个按钮,这些按钮做同样的事情,所以我想创建一个通用的功能。但首先我需要知道他按钮的名称(XML ID)。
I have 24 buttons in my layout, all these buttons do something similar so I want to create a generic function. But first I need to know the name (xml id) of he button.
按钮这在XML code:
This the XML code of the button:
<Button
android:id="@+id/add_04"
android:layout_width="42dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:background="@xml/zbuttonshape"
android:onClick="onClick"
android:text="@string/mas" />
我设置的android:的onClick =的onClick所有按钮
I set android:onClick="onClick" for all the buttons.
在我的活动我一直的onClick创建一个新的功能:
In my activity I've create a new function onClick:
这在code我尝试过:
This the code I've tried:
public void onClick(View v) {
String name = v.getContext().getString(v.getId());
String name2 = context.getString(v.getId());
String name3 = getString(v.getId());
String name4 = getResources().getString(v.getId());
}
但是,当我试图让名(在这种情况下,add_04),我总是得到假。
But when I try to get the name (in this case "add_04") I always get "false".
最后我发现用下面的code的解决方案:
Finally I've found a solution with the following code:
import java.lang.reflect.Field;
String name5 = null;
Field[] campos = R.id.class.getFields();
for(Field f:campos){
try{
if(v.getId()==f.getInt(null)){
name5 = f.getName();
break;
}
}
catch(Exception e){
e.printStackTrace();
}
}
我的问题是,如果没有一个更简单的方法来获得这个ID?
My question is if Is not there an easier way to get this ID?
在此先感谢。
推荐答案
这种方法是错误的开始。如果你想要一块任意数据(如字符串),以便联系起来,这就是标记
是。该ID是数字,它更好地保持下去。
The approach is misguided to begin with. If you want to associate a piece of arbitrary data (e. g. a string) with a view, that's what tag
is for. The ID is numeric and it better stay that way.
这篇关于更简单的方法来获得视图的ID(字符串)通过其ID(INT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!