2013-07-24 214 views
4

我创建基于RelativeLayout在代码安卓:从膨胀的布局

我在XML R.layout.menu_layout(风格,绘制背景,边缘,高度)中定义的布局基本

一类我自己的布局自定义视图

如果我不需要一个类,那么我会打电话吹气做到这一点:

RelativeLayout menuLayout = (RelativeLayout)inflater.inflate(R.layout.menu_layout, root); 

但我想可以叫我自己的类,而不是

MenuLayout menuLayout = new MenuLayout(myparams); 

由于我需要创建一个类,我需要以某种方式继承构造函数中的R.layout.menu_layout,我该怎么做?我猜在视图中没有this.setLayout(res);this.setResource(res);。也许我可以在视图构造函数中使用其他两个参数,但是我没有找到任何教程如何做到这一点。

+4

可以改写了一下你的问题? – Blackbelt

+0

做了新的信息帮助吗? – Ragnar

回答

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); 

可以更改PARAMS我想构造

+0

不只是将相对布局放入相对布局?我正在考虑将此作为解决方案,但我希望有一些更清洁的方式 – Ragnar

+0

是的,但这是我想出的。我认为这是一个干净而易于理解的解决方案。由于不必要的'RelativeLayout',它可能会得到改进。 – Johannes