2016-11-04 25 views
3

在一個片段中,我有一個打開PopupWindow的按鈕。ButterKnife爲什麼不能綁定私有內部類中的字段?

private class onMenuClickListener implements View.OnClickListener { 
    @BindView(R.id.popup_radiogroup) RadioGroup popupRadioGroup; 
    @BindView(R.id.popup_textview) TextView popupTextView; 

    PopupWindow popupWindow = getPopupWindow(R.layout.popup_window); 

    @Override 
    public void onClick(View v) { 
     ButterKnife.bind(this, popupWindow.getContentView()); 
     popupWindow.showAsDropDown(menuButton); 
    } 
} 
private PopupWindow getPopupWindow(int layout_resource_id) { 
    LayoutInflater inflater = (LayoutInflater) getContext() 
      .getSystemService(LAYOUT_INFLATER_SERVICE); 
    View popupView = inflater.inflate(layout_resource_id,(ViewGroup)getView()); 

    return new PopupWindow(popupView, 
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT,true); 
} 

當我嘗試運行此代碼時,出現此錯誤:「@BindView字段可能不包含在私有類中。」 ButterKnife如何不能訪問私人內部類,但它可以自由訪問受保護的內部類?

回答

5

它們不能是私人的,否則它無法訪問它。 會爲您生成一些代碼,其中包含您不願意爲您編寫的所有樣板代碼。當你寫ButterKnife.bind(this),其中this在這種情況下是Activity,它試圖通過你提供的參考訪問每個註釋成員,並通過顯式強制轉換執行findViewById。如果該成員是私人的,它不能被訪問(基本的Java)。

+2

'protected'啓用包可見性。看看[這裏](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) – Blackbelt

+1

主要原因還在於它依賴於註釋而不是純粹的反射(它可以*做的地方一些魔術),但它會臃腫和更復雜,因爲它需要橋接訪問。將它們標記爲可見是沒有錯的,事實上,我認爲它不應該受到保護,它們應該什麼也沒有(default = package)。 –

相關問題