Android:从充气布局创建自定义视图

5
我正在创建一个基于代码中的RelativeLayout类的自定义布局。我的布局基础已经在XML文件R.layout.menu_layout中定义好了,包括样式、背景图、边距和高度。
如果我不需要一个类的话,我可以调用inflater函数来实现这个目的:
RelativeLayout menuLayout = (RelativeLayout)inflater.inflate(R.layout.menu_layout, root);

但我想调用自己的类

MenuLayout menuLayout = new MenuLayout(myparams);

由于我需要创建一个类,因此我需要在构造函数中继承R.layout.menu_layout,我该怎么做呢?我猜View里没有this.setLayout(res);或者this.setResource(res);。也许我可以使用View构造函数中的其他两个参数,但是我也没有找到任何教程如何操作。


4
你能稍微改一下你的问题吗? - Blackbelt
新的信息有帮助吗? - Ragnar
1个回答

2
public class MenuLayout extends RelativeLayout {
    public MenuLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public MenuLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MenuLayout(Context context) {
        super(context);
        initView(context);
    }

    private void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.menu_layout, null);
        addView(view);
    }
}

现在您可以使用。
MenuLayout menuLayout = new MenuLayout(myparams);

我认为您可以更改参数的构造函数。


这不是将相对布局放入另一个相对布局中吗?我也考虑过这种方法,但我希望有更简洁的方式。 - Ragnar
是的,它确实可以,但这就是我想出来的解决方案。我认为这是一个干净且易于理解的解决方案。由于不必要的“RelativeLayout”,它可能会得到改进。 - Johannes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接