[英]How to resolve the error: Java class cannot be instantiated in XML layout in android?
public class BottomToolbar extends RelativeLayout {
private Spinner circleSpinner;
private ImageButton operatorImageButton;
private ToggleButton conntypeToggleButton;
private Context context;
public BottomToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.toolbar, this);
this.context = context;
circleSpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
context, R.array.circlesarray,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
circleSpinner.setAdapter(adapter);
}}
The above code creates a toolbar whose layout is defined in XML. 上面的代码创建了一个工具栏,其布局以XML格式定义。 But in XML view it shows the following error:
但在XML视图中,它显示以下错误:
The following classes could not be instantiated: - com.example.BottomToolbar
无法实例化以下类: - com.example.BottomToolbar
If I comment these lines the error goes: 如果我评论这些行错误:
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
context, R.array.circlesarray,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
circleSpinner.setAdapter(adapter);
Please help, I suspect there is something wrong with "context" in Array Adapter declaration. 请帮忙,我怀疑Array Adapter声明中的“context”有问题。
--Thanks in advance - 提前致谢
Try 尝试
public BottomToolbar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context);
}
public BottomToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public BottomToolbar(Context context) {
super(context);
initView(context);
}
public void initView(Context context) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.toolbar, this);
this.context = context;
circleSpinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
context, R.array.circlesarray,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
circleSpinner.setAdapter(adapter);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.