简体   繁体   中英

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. But in XML view it shows the following error:

The following classes could not be instantiated: - 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM