安卓:从膨胀的布局自定义视图 [英] Android: custom view from inflated layout

查看:185
本文介绍了安卓:从膨胀的布局自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建基于 RelativeLayout的为code类我自己的布局

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

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

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

不过,我想在调用我自己的类,而不是

  MenuLayout menuLayout =新MenuLayout(myparams);

因为我需要创建一个类,我需要以某种方式继承 R.layout.menu_layout 在构造函数中,我该怎么办呢?我想有没有 this.setLayout(RES); this.setResource(RES); 在View。也许我可以使用View构造函数中的另外两个参数,但我没有找到任何教程如何做,要么。


解决方案

 公共类MenuLayout扩展RelativeLayout的{
    公共MenuLayout(上下文的背景下,ATTRS的AttributeSet,诠释defStyle){
        超(背景下,ATTRS,defStyle);
        initView(上下文);
    }    公共MenuLayout(上下文的背景下,ATTRS的AttributeSet){
        超(背景下,ATTRS);
        initView(上下文);
    }    公共MenuLayout(上下文的背景下){
        超级(上下文);
        initView(上下文);
    }    私人无效initView(上下文的背景下){
        查看查看= LayoutInflater.from(上下文).inflate(R.layout.menu_layout,NULL);
        addView(视图);
    }
}

现在你可以使用

  MenuLayout menuLayout =新MenuLayout(myparams);

您可以更改构造函数PARAMS我认为

I am creating my own layout based on RelativeLayout as a class in code

I have basics of the layout defined in XML R.layout.menu_layout (style, drawable for background, margin, height)

If I would not need a class then I would call inflater to do this:

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

But I would like to be calling my own class instead

MenuLayout menuLayout = new MenuLayout(myparams);

Since I need to create a class I need to somehow inherit the R.layout.menu_layout in constructor, how can I do that? I guess there is no this.setLayout(res); or this.setResource(res); in View. Maybe I can use the other two parameters in View constructor but I did not find any tutorial how to do that either.

解决方案

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

now you can use

MenuLayout menuLayout = new MenuLayout(myparams);

you can change constructors for params i think

这篇关于安卓:从膨胀的布局自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆