【问题标题】:Clickable image - android可点击的图像 - 安卓
【发布时间】:2017-03-08 00:34:40
【问题描述】:

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

    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: 在活动中找不到方法 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();
}

【问题讨论】:

    标签: android image click clickable-image


    【解决方案1】:

    正如其他人所说:将其设为 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 处理程序可以为您节省大量输入,还可以避免匿名内部类的需要,这有利于内存占用。

    【讨论】:

    • 好的,这个可行,但现在我的图像在一个按钮内.. 所以它正在阻止我的布局。为了解决这个问题,我在 xml 中添加了 android:background="@null" 行,一切都很完美!
    • 正确使用的背景是android:background="?android:selectableItemBackground"
    【解决方案2】:

    ImageButton 做你想做的事吗?

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

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

    【讨论】:

    • 我尝试使用 clickImage(View view) 但不起作用,原因是 OnClickListner.. 如果图像按钮是透明的并且仅显示图像(无按钮),我可以使用它。
    • 哦,如果你在 onCreate 中显式设置了点击监听器,你的布局中不应该有 onClick 属性。
    • 我试过从代码中去掉android:onClick="clickImage",结果是点击的时候什么都没有发生。
    【解决方案3】:

    【讨论】:

      【解决方案4】:

      使用ImageButton ;)

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 2015-04-20
          • 1970-01-01
          • 2011-05-17
          • 1970-01-01
          • 1970-01-01
          • 2011-12-11
          • 1970-01-01
          • 2017-04-01
          相关资源
          最近更新 更多