How to run a custom view with three-argument version constructor on pre-Honeycomb devices?

▼魔方 西西 提交于 2019-12-25 02:18:29

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/13405061/how-to-run-a-custom-view-with-three-argument-version-constructor-on-pre-honeycom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!