可点击图像 - Android
-
24-10-2019 - |
题
如何使图像可单击?我已经尝试了一些方法,但没有成功。这是我尝试过的最后一个代码(可单击但会出现错误):
ImageView btnNew = (ImageView) findViewById(R.id.newbutton);
btnNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do stuff
}
});
这是XML的部分:
<ImageView
android:src="@drawable/tbnewbutton"
android:text="@string/hello"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/newbutton"
android:clickable="true"
android:onClick="clickImage"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" />
运行此代码并单击图像时,我会收到此错误:
01-24 19:14:09.534:错误/androidruntime(1461):java.lang.illegalstateException:在活动中找不到方法clickimage(view)
这是解决方案:
XML:
<ImageButton
android:src="@drawable/tbnewbutton"
android:text="@string/hello"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/newbutton"
android:clickable="true"
android:onClick="clickNew"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@null" />
编码 :
public void clickNew(View v)
{
Toast.makeText(this, "Show some text on the screen.", Toast.LENGTH_LONG).show();
}
解决方案
正如其他人所说的: ImageButton
并定义其onClick属性
<ImageButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="left"
android:onClick="scrollToTop"
android:src="@drawable/to_top_button"
/>
该图像在此处编码在文件res/drawable/to_top_button.png中。如果用户单击按钮,则该方法 scrollToTop()
叫做。需要在将布局设置为使用的类中 ImageButton
作为内容布局。
public void scrollToTop(View v) {
...
}
以这种方式定义OnClick处理程序可以节省大量打字,还可以防止需要匿名的内部类,这对内存足迹有益。
其他提示
做一个 ImageButton 做你想要什么?
您收到的错误消息意味着您的活动中没有与OnClick处理程序相匹配的方法。
你应该有类似的东西 clickImage(View view)
在您的活动中,点击处理实现。
您可以只使用ImageButton类...http://developer.android.com/reference/android/widget/imagebutton.html
用一个 ImageButton ;)
当在XML中单击图像时,您已经设置了onclick方法来调用“ clickimage”,但是您尚未在代码中创建ClickImage方法。您根本不需要设置OnClick侦听器。只需从XML实现该方法,就应该设置。
不隶属于 StackOverflow