0

我有一个自定义视图,它使用以下构造函数扩展了 LinearLayout:

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

public VoiceRecorderLayout(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
    }

    public VoiceRecorderLayout(Context context, AttributeSet attrs, int defStyle) 
{       
    super(context, attrs, defStyle);
    this.context = context;   
    loadViews();    
}

仅当我在 api 低于 11 的设备或模拟器上运行它时,我的应用程序才会崩溃。崩溃的原因是我在 android 开发人员 google 组中找到的三参数构造函数:

**"The three-argument version of LinearLayout constructor is only available with API 11 and higher -- i.e. Android 3.0.
This dependency has to be satisfied at runtime by the actual Android version running on the device."**

有没有办法可以在旧设备(例如 android 2.3.3)中使用此视图?

这是一个日志猫:

11-15 13:34:20.121: E/AndroidRuntime(408): Caused by: java.lang.reflect.InvocationTargetException
11-15 13:34:20.121: E/AndroidRuntime(408):  at java.lang.reflect.Constructor.constructNative(Native Method)
11-15 13:34:20.121: E/AndroidRuntime(408):  at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
11-15 13:34:20.121: E/AndroidRuntime(408):  at android.view.LayoutInflater.createView(LayoutInflater.java:505)
11-15 13:34:20.121: E/AndroidRuntime(408):  ... 21 more
11-15 13:34:20.121: E/AndroidRuntime(408): Caused by: java.lang.NoSuchMethodError: android.widget.LinearLayout.<init>
11-15 13:34:20.121: E/AndroidRuntime(408):  at edu.neiu.voiceofchicago.support.VoiceRecorderLayout.<init>(VoiceRecorderLayout.java:102)
11-15 13:34:20.121: E/AndroidRuntime(408):  at edu.neiu.voiceofchicago.support.VoiceRecorderLayout.<init>(VoiceRecorderLayout.java:97)
11-15 13:34:20.121: E/AndroidRuntime(408):  ... 24 more
4

1 回答 1

4

In cases like this, it is easier not to chain the constructors, and place your custom setup code into an init() style method so that you don't have to try and branch your code based on platform version.

public VoiceRecorderLayout(Context context) {
    super(context);
    init(context);
}

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

public VoiceRecorderLayout(Context context, AttributeSet attrs, int defStyle) {       
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context) {
    this.context = context;   
    loadViews();    
}
于 2012-11-15T20:05:00.447 回答