2013-05-03 20 views
0

我試圖使用操作欄中的複選框,即時通訊使用actionbarsherlock。 我已經非常努力地獲得了複選框的工作,現在我已經制作了UI(使用setCustomView方法),但是我被困在複選框的檢查事件中,我做了一些類似問題的研究但得到的答案是「複選框不能用於操作欄,它只能用於submemus或等」,我懷疑和想知道是否有辦法讓它工作... 這裏是我的用戶界面: enter image description here如何獲取操作欄工作的複選框(由setCustomView添加)?

這裏是我的CustomView XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="fill_parent" 
    android:layout_gravity="right" 
    android:gravity="center_vertical" > 

    <CheckBox 
     android:id="@+id/action_anoni_check" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:layout_gravity="center_vertical" 
     android:checked="false" 
     android:gravity="center" 
     android:text="@string/anonymity" /> 

</LinearLayout> 

這是我如何增加它在我的UI:

ActionBar actionBar = getSupportActionBar(); 
    actionBar.setCustomView(R.layout.write_actionbar_top); 

回答

0

您可能希望創建類的實例變量和虛增您write_actionbar_top視圖,所以你必須對它的引用,然後添加一個onCheckListener到您的複選框:

private CheckBox mCheckbox; 

... 
... 

mCheckbox = getLayoutInflater().inflate(R.layout.write_actionbar_top, null,false); 

mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
    @Override 
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 
     if(isChecked){ 
      //DO YOUR on CHECK ACTION IN HERE 
     } 

    } 
} 

ActionBar actionBar = getSupportActionBar(); 
actionBar.setCustomView(mCheckbox); 

此代碼尚未經過測試,但你應該明白。

也有一些更多的方式來獲得點擊或在您的CheckBox視圖檢查行動在這裏 - >Android: checkbox listener

1

我知道這是一個老問題,但我想我會附和,因爲我不能讓克雷格的解決方案正常工作。 「預期」的做法是:

getSupportActionBar().setDisplayShowCustomEnabled(true); 
    getSupportActionBar().setCustomView(R.layout.write_actionbar_top); 

    CheckBox mCheckbox = (CheckBox) getActionBar().getCustomView().findViewById(R.id.action_anoni_check); 
    mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if(isChecked){ 
       //DO YOUR on CHECK ACTION IN HERE 
      } 
     } 
    }); 
+0

這是唯一適用於我的解決方案。非常感謝。 – 2014-09-22 07:39:49