通过 ID 访问以编程方式生成的 CustomView 对象
Access programmatically generated CustomView objects by their ids
我正在尝试通过这种方式从 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 cannot be cast to
startup.project.views.ObjectView
您已将自定义视图添加到 relativeLayout。因此,您必须使用 relativeLayout
来获取自定义视图。
尝试使用
ObjectView object = relativeLayout.findViewById(componentsIds);
而不是
ObjectView object = findViewById(componentsIds);
我正在尝试通过这种方式从 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 cannot be cast to startup.project.views.ObjectView
您已将自定义视图添加到 relativeLayout。因此,您必须使用 relativeLayout
来获取自定义视图。
尝试使用
ObjectView object = relativeLayout.findViewById(componentsIds);
而不是
ObjectView object = findViewById(componentsIds);