更简单的方法来获得视图的ID(字符串)通过其ID(INT)视图、字符串、方法来、简单

2023-09-05 11:00:21 作者:汗味满满不敢靠近

我是新与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.