嗨,我是android开发的新手,我在这方面遇到了麻烦。当我单击某个图像时,我想在textView上显示我的imageView的源名称。为了更深入地理解,这里是我的image clickListener的硬编码(希望有人也能帮助我改进我的编码)。
int ctr = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
//DECLARE CLICK LISTENERS ON OBJECTS
ImageView ImageView1 = (ImageView)findViewById(R.id.imageView1);
ImageView1.setOnClickListener(this);
ImageView ImageView2 = (ImageView)findViewById(R.id.imageView2);
ImageView2.setOnClickListener(this);
...
public void onClick(View v) {
//CHANGE TEXT VIEW TEXT BASED ON THE CTR VALUE
TextView TextView1 =(TextView)findViewById(R.id.textView1);
//I WANT TO CHANGE THIS ONE TO DISPLAY SRC INSTEAD OF THE CTR VALUE
TextView1.setText(Integer.toString(ctr));
}在这里,我不想显示CTR值,而是想要显示我在设置的两个图像之间单击的任何图像的src名称。我相信这是可能的。谢谢。
发布于 2011-06-24 13:03:43
您可以使用下面的方法从id中获取资源的名称:
/**
* Determines the Name of a Resource,
* by passing the <code>R.xyz.class</code> and
* the <code>resourceID</code> of the class to it.
* @param aClass : like <code>R.drawable.class</code>
* @param resourceID : like <code>R.drawable.icon</code>
* @throws IllegalArgumentException if field is not found.
* @throws NullPointerException if <code>aClass</code>-Parameter is null.
* <code>String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);</code><br>
* Then <code>resName</code> would be '<b>icon</b>'.*/
public String getResourceNameFromClassByID(Class<?> aClass, int resourceID)
throws IllegalArgumentException{
/* Get all Fields from the class passed. */
Field[] drawableFields = aClass.getFields();
/* Loop through all Fields. */
for(Field f : drawableFields){
try {
/* All fields within the subclasses of R
* are Integers, so we need no type-check here. */
/* Compare to the resourceID we are searching. */
if (resourceID == f.getInt(null))
return f.getName(); // Return the name.
} catch (Exception e) {
e.printStackTrace();
}
}
/* Throw Exception if nothing was found*/
throw new IllegalArgumentException();
}例如,使用:
String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.icon);结果将为icon
发布于 2011-06-24 13:40:25
在xml中,您可以添加标记来设置带有图像任何信息
示例
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageview1"
android:background="@drawable/bg"
android:tag="bg"/>动态地,您可以使用imageView.setTag("any name")来设置任何数据以及图像和imageView.getTag()来检索图像信息
String backgroundImageName = (String) imageView.getTag();发布于 2013-05-31 15:06:11
尝试此
String resName = getResourceNameFromClassByID(R.drawable.class, R.drawable.imagename);https://stackoverflow.com/questions/6463243
复制相似问题