可点击的图片 - android

use*_*146 15 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
          }

        });      
Run Code Online (Sandbox Code Playgroud)

这是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" />
Run Code Online (Sandbox Code Playgroud)

运行此代码,然后单击图像我收到此错误:

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" />
Run Code Online (Sandbox Code Playgroud)

代码 :

    public void clickNew(View v)
{
    Toast.makeText(this, "Show some text on the screen.", Toast.LENGTH_LONG).show();
}
Run Code Online (Sandbox Code Playgroud)

Hei*_*upp 25

正如其他人所说:make this 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"
/>
Run Code Online (Sandbox Code Playgroud)

此处的图像以文件res/drawable/to_top_button.png编码.如果用户单击该按钮,scrollToTop()则调用该方法.需要在将Layout设置ImageButton为其内容布局的类中声明此方法.

public void scrollToTop(View v) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

以这种方式定义OnClick处理程序可以节省大量的输入,并且还可以防止对匿名内部类的需要,这有利于内存占用.

  • 好吧,这个可以工作,但现在我的图像在按钮内..所以它正在制动我的布局.为了解决这个问题,我在xml中添加了android:background ="@ null"这一行,完美无缺! (9认同)