0

我有一个与此类似的 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 创建小部件而不是将其作为子项附加会更有意义。我这样做的方式是拥有自定义小部件的唯一方法吗?还是有更清洁的方法?

谢谢,

布拉德

4

1 回答 1

1

您可以让小部件扩展 TableLayout,而不是扩展 LinearLayout。

然后,在您的 Merge 标记中,只需包含您希望将其添加到小部件中的行列表。

这消除了额外的线性布局。

例子:

<merge ... >
    <TableRow ... />
    <TableRow ... />
    <TableRow ... />
    <TableRow ... />
</merge>
于 2012-06-25T02:07:18.873 回答