【发布时间】:2015-09-30 03:20:41
【问题描述】:
/* Code snipet from the MainActivity */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Linear layout */
LinearLayout layout = (LinearLayout)findViewById(R.id.main_container);
/* Creating two similar custom views */
CustomView row1 = new CustomView(this); /* First row */
CustomView row2 = new CustomView(this); /* second row */
layout.add(row1,0);
layout.add(row2,1);
}
CustomView.java
public class CustomView extends View {
public final String TAG = "CustomView";
Context context;
private Drawable backgroundDrawable;
Rect backGroundDrawableRect;
public TextMessageView(Context context) {
super(context);
this.context = context;
backgroundDrawable = ContextCompat.getDrawable(context,R.drawable.background_drawable);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
backGroundDrawableRect.left = left;
backGroundDrawableRect.right = right;
backGroundDrawableRect.bottom = bottom;
backGroundDrawableRect.top = top;
backgroundDrawable.setBounds(backGroundDrawableRect);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/* 100 pixel height for the view */
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),100);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(backgroundDrawable != null) {
backgroundDrawable.draw(canvas);
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
问题是在线性布局的第二行中添加的视图没有显示出来。在调试过程中,当我在开发人员选项中启用“显示布局绑定”时,我发现第二行中的视图占用了所需的空间,但没有显示可绘制的内容。
【问题讨论】:
标签: android android-linearlayout android-custom-view