[英]Custom View not adding subviews
这是我的自定义视图:
public class FilterView extends RelativeLayout{
public FilterView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init(){
//To test, I add just a test button that will change the color of the view
Button b = new Button(getContext());
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) { setBackgroundColor(Color.GREEN); }
});
b.setText("TEST");
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(100, 100);
addView(b, lay);
//Also have tried without settings the layoutparams...
setBackgroundColor(Color.BLUE);
}
}
我将这样的自定义视图添加到这样的活动中(红色背景):
<com.example.android.FilterView android:id="@+id/filter"
android:layout_width="100dip"
android:background="#FF0000"
android:layout_height="100dip"/>
结果是颜色的视图... BLUE,在init()中设置的颜色,因此init中的代码被很好地调用了。 但是,视图内部没有任何内容,只有蓝色,没有名为“ TEST”的按钮,也没有可单击的区域,因为无论我单击何处,视图都不会变为绿色
抱歉,我犯了一个可怕的错误,
我的自定义视图正在重新实现onLayout方法,而没有调用它的超级方法...添加超级解决了该问题。 很抱歉打扰您这个愚蠢的问题。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
完成这条线
addView(b, lay);
与
this.addView(b, lay);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.