java - 通过 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
解决方案
您已将自定义视图添加到 relativeLayout。因此,您必须使用relativeLayout
来获取该自定义视图。
尝试使用
ObjectView object = relativeLayout.findViewById(componentsIds);
代替
ObjectView object = findViewById(componentsIds);
推荐阅读
- jekyll - 不使用 Jekyll 评估的 Liquid 语法
- objective-c - 以编程方式调用按钮操作导致 NSInvalidArgumentException
- syntax - 'static 可以放在结构声明中吗?
- microsoft-graph-api - 拒绝访问以在消息上添加 Microsoft Graph 架构扩展
- r - 为什么我不能在 R 中使用 apply 函数将 .rda 文件加载到 R 工作区?
- python - 'Student' 对象没有属性 'print_details'
- c# - 在加载 aspx 页面时显示加载图像和文本
- ruby-on-rails - Rails 5 控制台查询来计算数据库中的所有记录?
- flutter - 在颤动中获取不同位置的当地时间
- c# - 为什么使用 IAsyncEnumerable 比返回异步/等待任务慢
?