Inflating a view from inside the View constructor (Android)
I am using LayoutInflater to inflate the innards of a View in the View's constructor, as follows:
public class TrackHeader extends RelativeLayout {
public TrackHeader( Context context ) {
super( context );
final LayoutInflater inflater = getLayoutInflater( );
final RelativeLayout view = (RelativeLayout) inflater.inflate(
R.layout.trackheader, this, true );
< more here >
}
(I have also tried the following)
public TrackHeader( Context context ) {
super( context );
final LayoutInflater inflater = getLayoutInflater( );
final RelativeLayout view = (RelativeLayout) inflater.inflate(
R.layout.trackheader, this, false );
addView( view, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) );
< more here >
}
}
The XML is simple enough:
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/andro开发者_如何学运维id"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView android:id="@+id/trackNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
android:textSize="16dip"
/>
<Button android:id="@+id/waveformBtn"
android:layout_width="match_parent"
android:layout_height="40dip"
android:layout_below="@+id/trackNumber"
android:layout_gravity="center_horizontal"
android:textSize="12dip"/>
<CheckBox android:id="@+id/enabledCheck"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/waveformBtn"
android:layout_gravity="center_horizontal"
android:textSize="12dip"/>
<CheckBox android:id="@+id/loopingCheck"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/enabledBtn"
android:layout_gravity="center_horizontal"
android:textSize="12dip"/>
</RelativeLayout>
The reason I'm inflating it this way is that the class (TrackHeader) is a nested/inner class and that seems to stop me from referring to the class directly in the XML. Well, when inflating, the layout doesn't work. The top node (RelativeLayout) gets sized correctly to fill the TrackHeader, but the children views don't get sized at all and remain (0, 0, 0, 0). Curious if any Android aficionados out there can nudge me in the right direction...
Thanx in advance and Happy coding! -E.
I'm not sure that it explains why none of the child views get sized, but the "layout_below" attribute of the "loopingCheck" element should probably be "@+id/enabledCheck" rather than "@+id/enabledBtn". Other than that, no obvious problems jump out.
精彩评论