我创建了一个自定义 View 。现在我想创建一个类,它有一些自定义 View 作为组件(可能是自定义 View 数组)。例如,像 Button b = new Button(this) 这样的东西,我如何将它应用到我的自定义 View ?
因为自定义 View 的构造函数是CustomView(Context context, AttributeSets attrs),而在我创建的新类中,没有context和attrs?
谢谢!
最佳答案
将此构造函数添加到您的自定义 View 类:
public CustomView(Context context) {
mContext = context
}
这是您将如何使用自定义 View :
如果您需要自定义 View 成为唯一 View :
CustomView cv = new CustomView(this);
setContentView(cv);
如果要将自定义 View 添加到父 View :
// inflate mainXML
View mainView = getLayoutInflater().inflate(R.layout.mainXML, null);
// find container
LinearLayout container = (LinearLayout) mainView.findViewById(R.id.container);
// initialize your custom view
CustomView view = new CustomView(this);
// add your custom view to container
container.addView(view);
setContentView(mainView);
顺便说一句,这也应该有效:
CustomView cv = new CustomView(this, null);
编辑 1:
使用嵌套的 for 循环:
LinearLayout childLL;
CustomView cv
for (int i = 0; i < 8; i++) {
childLL = new LinearLayout(this);
for (int j = 0; j < 8; j++) {
cv = new CustomView(this);
// set LayoutParams
childLL.addView(cv);
}
container.addView(childLL);
}
setContentView(container);
关于android - 如何创建新的自定义 View 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18284003/