如何使图片可点击?我尝试了一些方法,但没有成功。 这是我尝试的最后一个代码(可点击但出错):
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: ERROR/AndroidRuntime(1461): java.lang.IllegalStateException: Could not find a method clickImage(View) in the activity
解决方案如下:
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
作为其内容布局设置Layout的类中声明。
public void scrollToTop(View v) {
...
}
以这种方式定义 OnClick 处理程序可以为您节省大量输入,还可以避免匿名内部类的需要,这有利于内存占用。
关于android - 可点击的图像 - 安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4785544/