Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: custom view from inflated layout

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.

like image 880
Ragnar Avatar asked Nov 02 '22 17:11

Ragnar


1 Answers

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

like image 79
Johannes Avatar answered Nov 11 '22 11:11

Johannes