ric*_*ick 16 android button imageview ontouchlistener
我已经设置了一个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>
Run Code Online (Sandbox Code Playgroud)
来自: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
}
Run Code Online (Sandbox Code Playgroud)
+ - + - + - + - + - + -
我其他明智的工作正常,它知道你按什么按钮.我对这个Android JAVA很新.如果你们能帮助我,请告诉我.
bod*_*ker 20
编辑 - TL; DR:
View v; // handle to your view
String idString = v.getResources().getResourceEntryName(v.getId()); // widgetA1
Run Code Online (Sandbox Code Playgroud)
原版的:
我知道你发布以来已经有一段时间了,但是我正在处理类似的问题,我想我通过查看View类的Android 源代码找到了解决方案.
我注意到当你打印一个View(隐式调用toString())时,打印的数据包括布局文件中使用的ID String(你想要的那个),而不是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);
Run Code Online (Sandbox Code Playgroud)
在源代码中,Android还使用getResourcePackageName(id)和getResourceTypeName(id)构建完整的字符串:
String idString = res.getResourcePackageName(id) + ":" + res.getResourceTypeName(id)
+ "/" + res.getResourceEntryName(id);
Run Code Online (Sandbox Code Playgroud)
这会产生一些效果android:id/widgetA1.
希望有所帮助!
st0*_*0le 18
你不能得到那个widgetA1字符串......你总会得到一个整数.但是该整数对于该控件是唯一的.
所以你可以这样做来检查,按下了哪个按钮
int ID = iv.getId();
if(ID == R.id.widgetA1) // your R file will have all your id's in the literal form.
{
}
Run Code Online (Sandbox Code Playgroud)
小智 15
XML
android:tag="buttonA"
Run Code Online (Sandbox Code Playgroud)
SRC
Button.getTag().toString();
Run Code Online (Sandbox Code Playgroud)