2013-02-12 12 views
2

點擊監聽器我有一個imageview的 - 它有兩個屬性 - 可聚焦focusableintouchmode設置爲真正
Android的焦點監聽和關於ImageView的

<ImageView 
     android:id="@+id/ivMenu01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:focusable="true" 
     android:focusableInTouchMode="true" > 
    </ImageView> 

我已經實現了onFocusChangeListener在我的動態 -


@Override 
public void onFocusChange(View v, boolean hasFocus) { 
    switch (v.getId()) { 
    case R.id.ivMenu01: 

      if (hasFocus) { 
       ivMenu01.setImageBitmap(Utility 
         .getBitmap("Home_ford_focus.png")); // Focussed image 
      } else { 
       ivMenu01.setImageBitmap(Utility.getBitmap("Home_ford.png")); // Normal image 
      } 

     break; 

    default: 
     break; 
    } 

} 

另外,onClickListener -

case R.id.ivMenu01: 
       ivMenu01.requestFocus(); 
       Intent iFord = new Intent(HomeScreen.this, FordHome.class); 
       startActivity(iFord); 

break; 

現在,當我點擊ImageView的第一次點擊使焦點轉移到ImageView的第二次單擊執行的操作。 我不知道爲什麼會發生這種情況。
第一次點擊應該請求焦點以及執行操作。
任何有關如何做到這一點的幫助將不勝感激。

回答

7

這是小部件框架的設計方式。

當你看View.onTouchEvent()代碼,你會發現,只有當觀點採取重點點擊執行動作:

// take focus if we don't have it already and we should in 
    // touch mode. 
    boolean focusTaken = false; 
    if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 
     focusTaken = requestFocus(); 
    } 

    if (!mHasPerformedLongPress) { 
     // This is a tap, so remove the longpress check 
     removeLongPressCallback(); 

     // Only perform take click actions if we were in the pressed state 
     if (!focusTaken) { 
      // click 
     } 
    } 

因此,當你注意到了,第一次點擊,使觀看增益焦點。第二個將觸發點擊處理程序,因爲視圖已經有了焦點。

如果你想改變ImageView的位圖時,它的按下,你應該實現一個View.OnTouchListener並通過ImageView.setOnTouchListener()方法對其進行設置。該偵聽器應該或多或少是這樣的:

private View.OnTouchListener imageTouchListener = new View.OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     if (event.getAction() == MotionEvent.ACTION_DOWN) { 
      // pointer goes down 
      ivMenu01.setImageBitmap(Utility.getBitmap("Home_ford_focus.png")); 
     } else if (event.getAction() == MotionEvent.ACTION_UP) { 
      // pointer goes up 
      ivMenu01.setImageBitmap(Utility.getBitmap("Home_ford.png")); 
     } 
     // also let the framework process the event 
     return false; 
    } 
}; 

你也可以使用一個選擇又名狀態列表繪製對象來實現同樣的事情。請參閱參考:http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

+0

感謝您的回答。 – Anukool 2013-02-12 13:31:09