Reputation: 2119
I'm doing a custom view in Android. It's a simple combo of 2 TextViews inside a LinearLayout.
__________________________________
|TextView |TextView |
----------------------------------
My custom class is the following:
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();
}
}
This is my attr set:
<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>
And this is how I'm adding it:
<com.wally.pocket.widgets.Label
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:label_text="Test"
app:display_text="Test" />
But in the preview Screen i don't see anything. It's not drawing. When I launch the app it shows nothing. What am I missing?
Upvotes: 0
Views: 177
Reputation:
Your LinearLayout has nothing to do with your custom view. You just create a LinearLayout in constructor of your custom view but you never bond them together. You should extend LinearLayout instead of View since that is your parent view. Then instead of using layout.addView() use this.addView(). Let me know if you do not manage to do that.
Upvotes: 2