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

标签 android android-layout android-linearlayout android-view android-custom-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);
}

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

最佳答案

好的,我发现了一种方法。基本上,您需要继承通常在 XML 中定义的最顶层类,而不是直接继承 View 类。例如,如果您的自定义 View 需要一个 LinearLayout 作为其最顶层的类,那么您的自定义 View 应该简单地继承 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);
    }
}

子类化 LinearLayout 是“黑客”吗?据我所见。一些官方的 View 子类也是这样做的,比如 NumberPickerSearchView (即使他们从 XML 扩展他们的布局)。

经过思考,这其实是一个很明显的答案。

关于android - 如何以编程方式创建自定义 View 的布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14120419/

相关文章:

java - 使用 sleep 将方法暂停一秒钟

android - 使用 Google Service Plugin 3.2.0 的 Gradle 构建失败

java - 创建对象与读取 Json

java - Android ListView : Fixed number of rows for EVERY screen size

android - 在 fragment 中调用 getTag() 时总是返回 null

android - WebView 的 loadData 的编码问题

android - 对话框背景填充的默认颜色是什么?

android - 如何在水平 LinearLayout 中将元素右对齐?

java - 为什么我的 EditText 被布局覆盖?

android - 如何在动态创建的一组 editText 上设置 onFocusChangeListener()?