如何以编程方式创建自定义View的布局?

Xåp*_* - 19 android android-custom-view android-layout android-linearlayout android-view

在Activity中,您可以通过以下方式以编程方式创建LinearLayout:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    TextView tv1 = new TextView(this);
    tv1.setText("HELLO");
    ll.addView(tv1);

    TextView tv2 = new TextView(this);
    tv2.setText("WORLD");
    ll.addView(tv2);

    setContentView(ll);
}
Run Code Online (Sandbox Code Playgroud)

你如何在自定义View子类中做同样的事情?没有setContentViewonCreate方法......

Xåp*_* - 32

好的,我发现了一种方法.基本上,您不需要直接对View类进行子类化,而是需要子类化您通常在XML中定义的最顶层的类.例如,如果您的自定义视图需要将LinearLayout作为其最顶层的类,那么您的自定义视图应该只是子类化LinearLayout.

例如:

public class MyCustomView extends LinearLayout
{
    public MyCustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        setOrientation(LinearLayout.VERTICAL);
        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        TextView tv1 = new TextView(context);
        tv1.setText("HELLO");
        addView(tv1);

        TextView tv2 = new TextView(context);
        tv2.setText("WORLD");
        addView(tv2);
    }
}
Run Code Online (Sandbox Code Playgroud)

是否将LinearLayout子类化为"hack"?不是我能看到的.一些官方的View子类也是如此,比如NumberPickerSearchView(即使它们从XML中扩展了它们的布局).

经过反思,这实际上是一个非常明显的答案.