Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

android - Easier way to get view's Id (string) by its Id (int)

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.

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.

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" />

I set android:onClick="onClick" for all the buttons.

In my activity I've create a new function onClick:

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()); 
}

But when I try to get the name (in this case "add_04") I always get "false".

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();
    }
}

My question is if Is not there an easier way to get this ID?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

like this:

/**
 * @return "[package]:id/[xml-id]"
 * where [package] is your package and [xml-id] is id of view
 * or "no-id" if there is no id
 */
public static String getId(View view) {
    if (view.getId() == View.NO_ID) return "no-id";
    else return view.getResources().getResourceName(view.getId());
}

I use this in view constructors to make more meaningful TAGs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...