[英]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.