我有一个自定义视图,它使用以下构造器扩展了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?
这是一个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发布于 2012-11-16 04:05:00
在这种情况下,不链接构造函数会更容易,并将自定义设置代码放入init()样式的方法中,这样您就不必尝试根据平台版本来分支代码。
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
复制相似问题