我正在Android中進行自定義視圖。這是LinearLayout中2個TextViews的簡單組合。自定義視圖什麼都不顯示 - Android
__________________________________
|TextView |TextView |
----------------------------------
我的自定義類如下:
public class Label extends View {
private TextView label, display;
LinearLayout layout;
public Label(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.Label,
0,0
);
try{
layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
layout.setPadding(4,4,4,4);
layout.setLayoutParams(params);
layout.setOrientation(LinearLayout.VERTICAL);
label = new TextView(context);
label.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
display = new TextView(context);
display.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
label.setText(a.getString(R.styleable.Label_label_text));
display.setText(a.getString(R.styleable.Label_display_text));
layout.addView(label);
layout.addView(display);
}finally{
a.recycle();
}
}
public void setDisplay(String displayText){
display.setText(displayText);
invalidate();
requestLayout();
}
public void setLabel(String labelText){
label.setText(labelText);
invalidate();
requestLayout();
}
}
這是我ATTR集:
<resources>
<declare-styleable name="Label">
<attr name="label_text" format="string"/>
<attr name="display_text" format="string"/>
<attr name="drawable" format="color"/>
<attr name="label_position" format="enum">
<enum name="left" value="-1"/>
<enum name="center" value ="0"/>
<enum name="right" value="1"/>
</attr>
<attr name="display_position" format="enum">
<enum name="left" value="-1"/>
<enum name="center" value ="0"/>
<enum name="right" value="1"/>
</attr>
</declare-styleable>
</resources>
這就是我如何將它添加:
<com.wally.pocket.widgets.Label
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:label_text="Test"
app:display_text="Test" />
但在預覽屏幕上我什麼也沒看到。這不是繪畫。當我啓動應用程序時,它什麼都沒顯示。我錯過了什麼?
我認爲高度或寬度是0.你需要實現'onMeasure()' –