2011-01-24 102 views
15

如何讓圖像可點擊?我嘗試了一些方法,但沒有成功。 這裏的最後一個代碼我想(這是點擊,但得到的錯誤):可點擊圖像 - android

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

回答

24

作爲其它說:使這是一個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 /抽拉/ to_top_button.png這裏進行編碼。如果用戶點擊該按鈕,則調用方法scrollToTop()。此方法需要在將ImageButton設置爲內容佈局的佈局的類中聲明。

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

定義onclick處理這種​​方式可以節省大量的輸入,也使您無需匿名內部類,這對內存佔用有益。

3

是否一個ImageButton你想要做什麼?

您收到的錯誤消息意味着您的活動中沒有與onClick處理程序匹配的方法。

在點擊處理實現中,您應該在您的活動中使用類似clickImage(View view)的內容。

+0

我試過用clickImage(視圖視圖),但不起作用,導致OnClickListner ..如果一個imagebutton是透明的並且只顯示圖像(沒有按鈕),我可以使用它。 – user484146 2011-01-24 18:31:08

+0

呵呵,如果你在onCreate中明確地設置了點擊監聽器,你的佈局中就不應該有onClick屬性。 – 2011-01-24 18:32:26

0

你已經設置的onclick方法是點擊您的XML圖像時叫「clickImage」但是你還沒有在你的代碼中創建一個clickImage方法。你根本不需要設置onclick監聽器。只需從您的XML中實現該方法,您應該設置。