17

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

    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();
}
4

5 回答 5

27

正如其他人所说:使它成为一个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()则调用该方法。此方法需要在设置 Layout 的类中声明,并将其ImageButton作为其内容布局。

public void scrollToTop(View v) {
    ...
}

以这种方式定义 OnClick 处理程序可以为您节省大量输入,还可以避免使用匿名内部类,这有利于内存占用。

于 2011-01-24T18:51:03.860 回答
3

ImageButton做你想做的事吗?

您收到的错误消息意味着您的活动中没有与您的 onClick 处理程序匹配的方法。

您的活动中应该有类似clickImage(View view)点击处理实现的内容。

于 2011-01-24T18:22:16.577 回答
1

你可以只使用 ImageButton 类... http://developer.android.com/reference/android/widget/ImageButton.html

于 2011-01-24T18:22:26.193 回答
1

使用ImageButton ;)

于 2011-01-24T18:22:39.953 回答
0

您已将 onclick 方法设置为在 XML 中单击图像时调用“clickImage”,但尚未在代码中创建 clickImage 方法。您根本不需要设置 onclick 侦听器。只需从您的 XML 中实现该方法,您就应该设置好。

于 2011-01-24T18:24:49.343 回答