gpt4 book ai didi

java - 基于 LinearLayout 创建自定义组件,在 XML 中声明布局

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:31:34 24 4
gpt4 key购买 nike

我一直在尝试在 Android 1.5 中创建复合控件(如 described here ),但一直找不到任何好的示例来说明如何使用 XML 文件指定布局来执行此操作。我可以创建一个 Activity,然后在构造函数中使用以下代码加载 xml 文件:

setContentView(R.layout.main);

但是,我想在 LinearLayout 的子类中执行此操作 - 因此我可以在其他 XML 布局中使用此复合组件。类似的东西:

public class CustomView extends LinearLayout
{
public CustomView(Context context) {
super(context);
setupView();
}
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
setupView();
}
public void setupView()
{
setContentView(R.layout.custom); // Not possible
}
}

执行此操作的正确方法是什么?

最佳答案

您必须为您的自定义 View “扩充”布局:

LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.custom, this, true);

关于java - 基于 LinearLayout 创建自定义组件,在 XML 中声明布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com