【问题标题】:How to resolve the error: Java class cannot be instantiated in XML layout in android?如何解决错误:Java 类无法在 android 的 XML 布局中实例化?
【发布时间】:2011-06-27 14:34:42
【问题描述】:
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);
}}

上面的代码创建了一个工具栏,其布局在 XML 中定义。但在 XML 视图中显示以下错误:

无法实例化以下类: - com.example.BottomToolbar

如果我评论这些行,则会出现错误:

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

请帮忙,我怀疑数组适配器声明中的“上下文”有问题。

--提前致谢

【问题讨论】:

    标签: java android xml


    【解决方案1】:

    试试

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      相关资源
      最近更新 更多