android - 可点击的图像 - 安卓

标签 android image click clickable-image

如何使图片可点击?我尝试了一些方法,但没有成功。 这是我尝试的最后一个代码(可点击但出错):

    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/

相关文章:

javascript - Android 和 iOS Webview 中 html 和 javascript 文件的安全性

java - 为整个应用设置静音/取消静音复选框

html - 使图像仅通过其特定部分响应?

android - 使用 ButterKnife 了解点击 View

android - 为android编译PJSUA错误: undefined references

java - 具有移位字节的新 ByteBuffer(Java)?

jquery - Zazzle.com 使用 jQuery 的图像缩放效果

python - 检测连续图像的非/最小变化像素的最快方法

javascript - jquery click() 的纯 javascript 等价物?

python - 避免在笔记本中单击退出 wxPython TreeCtrl