【问题标题】:Access programmatically generated CustomView objects by their ids通过 id 访问以编程方式生成的 CustomView 对象
【发布时间】:2020-01-12 10:41:44
【问题描述】:

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

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 不能被强制转换为 启动.project.views.ObjectView

【问题讨论】:

  • 你的xml布局中有customview吗?
  • @VaikundamRaghul 不,所有属性都由代码分配,它们是从(按钮单击)等事件动态生成的
  • 请添加您的ObjectView。是从Button延伸出来的吗?
  • @Md.Asaduzzaman ObjectView 从 View 扩展而来。它是画布上的位图形状>
  • 尝试在onClick内使用relativeLayout.findViewById(componentsIds);

标签: java android android-custom-view custom-view


【解决方案1】:

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

尝试使用

ObjectView object =  relativeLayout.findViewById(componentsIds);

代替

ObjectView object =  findViewById(componentsIds);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 2018-09-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多