2017-06-01 101 views
2

我用AppBar,FloatingActionButtonRecyclerView創建了Activity。我實現了我自己的FAB,因爲我希望它可以被檢查。這是我的代碼:FloatingActionButton with checkable implementation

public class CheckableFloatingActionButton extends FloatingActionButton implements Checkable { 

    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; 

    private boolean checked = false; 
    private boolean broadcasting; 

    private OnCheckedChangeListener onCheckedChangeListener; 

    public interface OnCheckedChangeListener { 

     void onCheckedChanged(CheckableFloatingActionButton fab, boolean isChecked); 
    } 

    public CheckableFloatingActionButton(Context context) { 
     this(context, null); 
    } 

    public CheckableFloatingActionButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CheckableFloatingActionButton); 
     setChecked(a.getBoolean(R.styleable.CheckableFloatingActionButton_checked, false)); 
     a.recycle(); 

    } 

    @Override 
    public void setChecked(boolean checked) { 
     if (this.checked != checked) { 
      this.checked = checked; 
      refreshDrawableState(); 
      if (broadcasting) { 
       return; 
      } 

      broadcasting = true; 
      if (onCheckedChangeListener != null) { 
       onCheckedChangeListener.onCheckedChanged(this, this.checked); 
      } 

      broadcasting = false; 
     } 
    } 

    public void toggle(boolean animate) { 
     if (animate) { 
      setChecked(checked); 
      return; 
     } 
     checked = !checked; 
     jumpDrawablesToCurrentState(); 

    } 

    public void setOnCheckedChangeListener(OnCheckedChangeListener listener) { 
     onCheckedChangeListener = listener; 
    } 

    @Override 
    public boolean performClick() { 
     toggle(); 
     return super.performClick(); 
    } 

    @Override 
    public boolean isChecked() { 
     return checked; 
    } 

    @Override 
    public void toggle() { 
     setChecked(!checked); 
    } 

    @Override 
    public int[] onCreateDrawableState(int extraSpace) { 
     final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); 
     if (isChecked()) { 
      mergeDrawableStates(drawableState, CHECKED_STATE_SET); 
     } 
     return drawableState; 
    } 

} 

它的工作,直到我向上/向下滾動和隱藏/顯示FAB。正如你所看到的,FAB動畫可繪製而不是立即設置。這就是爲什麼(我認爲)該錯誤發生。有什麼辦法解決它?

link

回答

0

如果那是一個FloatingAcionsMenu可以使用時,它擴大了聽衆或沒有,你爲什麼不使用偵聽器時,它的擴展檢查,如果「選中」參數爲true,如果它填充drawable。

fam.setOnFloatingActionsMenuUpdateListener(new FloatingActionsMenu.OnFloatingActionsMenuUpdateListener() { 
     @Override 
     public void onMenuExpanded() { 
      if(checked){ 
      //do something 
      } 
     } 

     @Override 
     public void onMenuCollapsed() { 
     } 
    });