2011-03-09 61 views
0

我是很新的Android和我試圖使用自定義的多選列表視圖,其項目定義如下:選擇題ListView和按鈕:焦點問題

<?xml version="1.0" encoding="utf-8"?> 
<com.jroy.android.views.CheckableLinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" 
    android:gravity="left|center_vertical"> 
    <CheckBox 
     android:id="@+id/checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0" 
     android:background="@drawable/checkbox_selector" 
     android:button="@null" /> 
    <TextView 
     android:id="@+id/name" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" /> 
    <Button 
     android:id="@+id/btn_view" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0" 
     android:background="@drawable/button_view_selector" /> 
</com.jroy.android.views.CheckableLinearLayout> 

ListView控件的選擇模式被設置爲「選擇題」和CheckableLinearLayout是的LinearLayout的子類,它實現了勾選的接口方式如下:

public class CheckableLinearLayout extends LinearLayout implements Checkable { 

    private Checkable mCheckable;     

    @Override 
    protected void onFinishInflate() { 

     super.onFinishInflate(); 

     // Find checkable view 
     for (int i = 0, childCount = getChildCount(); i < childCount; ++i) { 
      View v = getChildAt(i); 
      if (v instanceof Checkable) { 
       mCheckable = (Checkable) v; 
       v.setFocusable(false); 
       v.setClickable(false); 
       break; 
      } 
     } 

    } 

    public CheckableLinearLayout(Context context) { 
     super(context); 
    } 

    public CheckableLinearLayout(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    @Override 
    public boolean isChecked() { 
     return (mCheckable != null) 
       ? mCheckable.isChecked() 
       : false; 
    } 

    @Override 
    public void setChecked(boolean checked) { 
     if (mCheckable != null) { 
      mCheckable.setChecked(checked); 
     } 
    } 

    @Override 
    public void toggle() { 
     if (mCheckable != null) { 
      mCheckable.toggle(); 
     } 
    } 

} 

的問題是,我無法檢查任何項目,這似乎是唯一的按鈕可以有焦點。我嘗試了不同的關於焦點的事情,但我沒有設法讓它正常工作...

什麼是正確的方法來做我想達到的目標? 謝謝,

回答

3

將行內的所有控件設置爲「不可聚焦」。現在情況並非如此,因爲Button未實現Checkable,因此在您的佈局中未獲得setFocusable(false)

 for (int i = 0, childCount = getChildCount(); i < childCount; ++i) { 
      View v = getChildAt(i); 
      v.setFocusable(false); 
      if (v instanceof Checkable) { 
       mCheckable = (Checkable) v; 
       v.setClickable(false); 
       break; 
      } 
     } 
+0

好的,謝謝你,現在我可以通過觸摸他們檢查一些項目,但是當我試圖以編程方式檢查它們(複選框#setChecked(布爾)或ListView#setItemChecked(INT,布爾))複選框的外觀沒有改變(但其狀態正確設置爲我想要的)... –

+0

對不起,我錯了,調用ListView#setItemChecked完美的作品。只是一個細節,而觸摸物品來檢查它,其中包含的按鈕也似乎處於「按下」狀態,有誰知道如何解決這個問題? –