我有一个自定义视图,我正在尝试填充GridLayout。自定义视图由一个圆圈内的TextView组成。我遇到的问题是我的自定义视图的onDraw()方法永远不会被调用,所以我总是以空白屏幕结束。当我用普通的TextView填充我的GridLayout时,它工作得很好,所以我猜测问题出在我的自定义视图的某处。自定义视图不会绘制在GridLayout中
我的onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_collection);
gl = (GridLayout) findViewById(R.id.grid_sample_collection);
gl.setColumnCount(9);
gl.setRowCount(9);
LayoutInflater inflater = LayoutInflater.from(this);
for(int i=0;i<gl.getRowCount();i++){
for(int j=0;j<gl.getColumnCount();j++){
SampleCollectionView sampleCollectionView = new SampleCollectionView(this);
sampleCollectionView.setLabelText(i + "." + j);
gl.addView(sampleCollectionView);
//Adding the TextViews shown below works just fine
//TextView t = new TextView(this);
//t.setText(i + "." + j);
//t.setTextSize(30f);
//t.setPadding(30, 30, 30, 30);
//gl.addView(t);
}
}
int childCount = gl.getChildCount();
for (int i= 0; i < childCount; i++){
final SampleCollectionView sampleCollectionView = (SampleCollectionView) gl.getChildAt(i);
//final TextView text = (TextView) gl.getChildAt(i);
sampleCollectionView.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Log.d("OnClickListener: ", "Clicked text: " + sampleCollectionView.getLabelText());
}
});
}
}
我的自定义视图:
public SampleCollectionView(Context context){
super(context);
init();
}
public SampleCollectionView(Context context, AttributeSet attrs) {
super(context, attrs);
//get the attributes specified in attrs.xml using the name we included
TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
R.styleable.SampleCollectionView, 0, 0);
try {
//get the text and colors specified using the names in attrs.xml
circleText = a.getString(R.styleable.SampleCollectionView_circleLabel); //0 is default
circleCol = a.getInteger(R.styleable.SampleCollectionView_circleColor, 0);
circleBorderCol = a.getInteger(R.styleable.SampleCollectionView_circleBorderColor, 0);
labelCol = a.getInteger(R.styleable.SampleCollectionView_labelColor, 0);
} finally {
a.recycle();
init();
}
}
public void init(){
mPaint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int viewWidthHalf = this.getMeasuredWidth()/2;
int viewHeightHalf = this.getMeasuredHeight()/2;
int radius = 0;
if(viewWidthHalf>viewHeightHalf)
radius=viewHeightHalf-10;
else
radius=viewWidthHalf-10;
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setAntiAlias(true);
mPaint.setColor(circleCol);
canvas.drawCircle(viewWidthHalf, viewHeightHalf, radius, mPaint);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(20);
canvas.drawText(circleText, viewWidthHalf, viewHeightHalf, mPaint);
}
编辑:一些测试后,我发现,我的自定义视图的身高和体重分别为0.使用setMinimumHeight和setMinimumWidth后他们实际上正在吸引并正在响应点击。现在唯一的问题是,由于某种原因,所有的自定义视图是完全不可见的...
编辑2:原来的视图不可见,因为我没有设置视图的属性像circleCol正确,这导致它们被设置为其默认值(0)。