我设置了一个 onTouch 类来确定我的 40 个按钮中的一个何时被按下。
我面临的问题是确定哪个按钮被按下了。
如果我使用:
int ID = iv.getId();
当我点击按钮“widgetA1”时
我收到以下 ID:
2131099684
我希望它返回字符串 ID“widgetA1”
来自:game.xml
<ImageView android:layout_margin="1dip" android:id="@+id/widgetA1" android:src="@drawable/image" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
来自:game.java
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView)v;
int ID = iv.getId();
String strID = new Integer(ID).toString();
Log.d(TAG,strID);
//.... etc
}
+-+-+-+-+-+-
否则我工作得很好,它知道你按的是什么按钮。我对这个 Android JAVA 很陌生。让我知道你们是否可以帮助我。
最佳答案
编辑 - TL;DR:
View v; // handle to your view
String idString = v.getResources().getResourceEntryName(v.getId()); // widgetA1
原文:
我知道你发帖已经有一段时间了,但我正在处理类似的问题,我想我通过查看 Android source code for the View class 找到了解决方案.
我注意到当您打印 View 时(隐式调用 toString()),打印的数据包括布局文件中使用的 ID 字符串(您想要的),而不是 getId() 返回的整数。所以我查看了 View 的 toString() 的源代码,以了解 Android 是如何获取这些信息的,它实际上并不太复杂。试试这个:
View v; // handle to your view
// -- get your View --
int id = v.getId(); // get integer id of view
String idString = "no id";
if(id != View.NO_ID) { // make sure id is valid
Resources res = v.getResources(); // get resources
if(res != null)
idString = res.getResourceEntryName(id); // get id string entry
}
// do whatever you want with the string. it will
// still be "no id" if something went wrong
Log.d("ID", idString);
在 source code , Android 还使用 getResourcePackageName(id)
和 getResourceTypeName(id)
来构建完整的字符串:
String idString = res.getResourcePackageName(id) + ":" + res.getResourceTypeName(id)
+ "/" + res.getResourceEntryName(id);
这会导致 android:id/widgetA1
的效果。
希望对您有所帮助!
关于安卓 : ImageView getID(); returning integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3920833/