首页 > 解决方案 > 通过 id 访问以编程方式生成的 CustomView 对象

问题描述

我正在尝试访问以这种方式View创建的button1自定义对象:button2

final Button button1 = (Button) findViewById(R.id.generate);
button1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        ObjectView object = new ObjectView(getApplicationContext());
        object.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        object.setId(componentsIds);
        relativeLayout.addView(object);

    }
});

final Button button2 = (Button) findViewById(R.id.useComponent);
button2.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       ObjectView object =  findViewById(componentsIds);
       object.bringToFront();
    }
});

但我得到这个错误:

java.lang.ClassCastException: android.widget.Button 不能转换为 startup.project.views.ObjectView

标签: javaandroidandroid-custom-viewcustom-view

解决方案


您已将自定义视图添加到 relativeLayout。因此,您必须使用relativeLayout来获取该自定义视图。

尝试使用

ObjectView object =  relativeLayout.findViewById(componentsIds);

代替

ObjectView object =  findViewById(componentsIds);

推荐阅读