2

我正在編寫需要在Android 2.3.3上運行的Android應用程序(yeay fragmentation!)。由於該版本,LinearLayout推出了一個額外的構造函數,所以我希望能夠做這樣的事情:向後兼容LinearLayout構造函數

public class ActionMenuTextItemView extends LinearLayout 
{ 
    public ActionMenuTextItemView(Context context, AttributeSet attrs, int defStyle) 
    { 
     if (android.os.Build.VERSION.SDK_INT >= 11) 
      super(context, attrs, defStyle); 
     else 
      super(context, attrs); 
    } 

它不工作,因爲super必須是第一行。有沒有辦法解決這個問題(除了構建APK的兩個版本)?很顯然,我可能會一直使用雙參數版本,但我想知道是否有更好的方法。

回答

0

你可以有兩個構造如下。在薑餅中使用一個,在Honeycomb中使用另一個。

public class ActionMenuTextItemView extends LinearLayout 
{ 
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    public ActionMenuTextItemView(Context context, AttributeSet attrs, int defStyle) 
    { 
     super(context, attrs, defStyle); 
    } 

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