0

I have a custom view that extends LinearLayout with the following contructors:

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();    
}

My application crashes only iff I run it on the devices or emulator with api lower than 11. The reason of the crash is a three argument constructor as I found on android developers google group:

**"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."**

Is there a way that I can use this view in the older devices such as with android 2.3.3?

Here is a logcat:

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 に答える