Basically as the title says. I have a class that extends LinearLayout and I want that LinearLayout to have a child TextView inside. The problem is, the TextView does not seem to appear.
Here is what I have so far, what exactly am I doing wrong?
Update: I Changed my code as following as you guys have suggested, and my TextView still does not appear....
public class CalendarCourseView extends LinearLayout {
private int height;
private int topMargin;
private Course course;
public CalendarCourseView(Context context, Course course, int topMargin,
int height) {
super(context);
final DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
this.topMargin = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, topMargin, displayMetrics);
this.height = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, displayMetrics);
this.course = course;
this.setBackgroundColor(course.getColor());
setTextView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), this.height);
((MarginLayoutParams) getLayoutParams()).topMargin = topMargin;
}
private void setTextView() {
TextView textView = new TextView(this.getContext());
LayoutParams params = new LayoutParams(new LinearLayout.LayoutParams(ViewGroup
.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
textView.setLayoutParams(params);
textView.setText(course.getName());
this.addView(textView);
}
}
Update: I pinned-point the problem. It is with onMeasure. I believe the TextView is not placed in the same position as the LinearLayout after height and topMargin change.
Update: Fixed it simply by changing calling super.onMeasure on onMeasure.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, this.height);
((MarginLayoutParams) getLayoutParams()).topMargin = topMargin;
}
I believe it is because setMeasuredDimension(int, int) only changes the dimension of the View and not the children. I would also have had to override onLayout. Calling the super.onMeasure also changes the children and simplified things.
onMeasureusually gets called more than once. Adding stuff there to the layout is usually a bad idea. And you should useMeasureSpec.getSize(widthMeasureSpec)and not just pass inwidthMeasureSpec, because it is not a size by itself.onFinishInflate(which only works if inflating it from xml), or add some check to prevent it from being added again