友
我创建了一个扩展Textview的UI组件“compTV”。它工作得很好。 现在我想创建一个UI组件“3compTV”,它只包含3个“compTV”,彼此相邻。
如果我只是扩展Activity,那么创建LinearLayout并添加3“compTV”的代码非常有效。 但是如何创建一个Component呢? 我必须为“3compTV”组件扩展什么类,以及还需要什么。 当我扩展compTV时,只会绘制一个对象。所以我想我必须扩展一个不同的类或采取其他方法解决这个问题。
感谢您的支持
public class 3compTV extends compTV{
Context ctx;
int layoutMaringLeft = 100;
int layoutMaringRight = 0;
int layoutMaringTop = 0;
int layoutMaringBottom = 0;
int amountOfComponents = 5;
public components(Context context) {
super(context);
ctx = context;
Log.d(ctx.getString(R.string.app_name), "components, Constructor1");
compTV comp1 = new compTV(ctx);
compTV comp2 = new compTV(ctx);
compTV comp3 = new compTV(ctx);
comp2.setLetter("A");
comp2.setState("grey");
comp3.setLetter("A");
comp3.setState("grey");
LinearLayout LL2 = new LinearLayout(ctx);
LL2.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(layoutMaringLeft, layoutMaringTop,
layoutMaringRight, layoutMaringBottom);
LL2.addView(comp1, layoutParams);
comp1.setLetter("H");
comp1.setState("green");
LL2.addView(comp2, layoutParams);
LL2.addView(comp3, layoutParams);
}
public components(Context context, AttributeSet attrs) {
super(context, attrs);
ctx = context;
Log.d(ctx.getString(R.string.app_name), "components, Constructor2");
}
public components(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
ctx = context;
Log.d(ctx.getString(R.string.app_name), "components, Constructor3");
}
}
答案 0 :(得分:0)
制作一个展开LinearLayout
并包含3个compTV
实例的视图。
public class 3CompTV extends LinearLayout {
public 3CompTV(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < 3; i++) {
addView(new CompTV(context));
}
}
}
我个人的偏好是将3个CompTV视图放在XML布局中,其父元素为<merge>
。这允许您在XML中指定其属性,如wrap_content
,我发现它更清晰。您可以将它们添加到自定义视图中,如下所示:
public class 3CompTV extends LinearLayout {
public 3CompTV(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(LinearLayout.VERTICAL);
View.inflate(context, R.id.three_comp_tvs, this);
}
}