[英]Custom View not showing: no height, but still width
在我当前的项目中,我陷入了死胡同。 我的自定义视图仅创建为显示特定的颜色,除非具有最小高度,否则不会在我的模拟器视图中显示(尽管它似乎在Eclipse编辑器中正确显示),但是它只有最小高度。确切的高度。 我希望它是match_parent
。
问题可能在于它在列表视图的项目布局中。
那是我的自定义视图的代码:
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ColorView extends View {
private int mColor;
private Context mContext;
private int width;
private int height;
public ColorView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ColorView, 0, 0);
try {
mColor = a.getColor(R.styleable.ColorView_color, 0xFFFFFF);
} finally {
a.recycle();
}
}
public void setColor(int hexColor) {
mColor = hexColor;
invalidate();
}
public void setColorFromResource(int resID) {
mColor = mContext.getResources().getColor(resID);
invalidate();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.d("DEBUG", Integer.toString(w) + " " + Integer.toString(h));
width = w;
height = h;
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(mColor);
Log.d("DEBUG", "drawn");
}
}
还有我的布局文件的简化版本:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:raabeapp="http://schemas.android.com/apk/res/com.example.myapp"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/row_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<com.example.myapp.ColorView
android:id="@+id/status_view"
android:layout_width="20dip"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dip"
android:minHeight="50dp"
raabeapp:color="#FF0000" />
<TextView
android:id="@+id/hour_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/status_view"
android:text="1"
android:textSize="@dimen/hour_textsize"
android:width="70dp" />
<TextView
android:id="@+id/text_hourtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/hour_view"
android:text="@string/hour_text"
android:textSize="@dimen/hourtext_textsize" />
好的,我想出了一种解决方法:
当我使用LinearLayout
而不是RelativeLayout
我得到了想要的结果。
看来问题出在RelativeLayout
。 如果有人知道这是为什么,或者我如何仍然可以使用RelativeLayout
我将非常感兴趣。 这个答案不能提供完整的解决方案,但是如果有人遇到我的问题,可以提供一个丑陋的解决方法。
将android:layout_height="match_parent"
用于您的RelativeLayout
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.