Android: custom view from inflated layout

主宰稳场 提交于 2019-12-10 15:53:14

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/17836695/android-custom-view-from-inflated-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!