我有一个与此类似的 XML 布局(XML 和代码要复杂得多,但为简洁起见,我已经简化了):
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="@+id/button01"
android:src="@drawable/key_01" />
<ImageButton
android:id="@+id/button02"
android:src="@drawable/key_02" />
<ImageButton
android:id="@+id/button03"
android:src="@drawable/key_03" />
</TableRow>
</TableLayout>
</merge>
我将此布局作为自定义小部件。
public class ThreeButtons extends LinearLayout
{
public ThreeButtons(Context context, AttributeSet attrs)
{
super(context, attrs);
final LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflator.inflate(R.layout.three_buttons, this);
if (!isInEditMode())
setClickListeners();
}
...
private void setClickListeners()
{
...
}
}
问题是我有一个我认为不应该存在的额外深度。即:实际的 ThreeButtons 类是一个 LinearLayout,它只有一个子元素,即膨胀的 XML。
我原以为直接从 XML 创建小部件而不是将其作为子项附加会更有意义。我这样做的方式是拥有自定义小部件的唯一方法吗?还是有更清洁的方法?
谢谢,
布拉德