简体   繁体   中英

How to make a .xml layout file the layout of a custom View?

I need to create widget similar to web tabs, so I have crated simple tabs.xml with linear laoyut inside and buttons, but I need additional logic to insert in that view so simple include tabs.xml in Activity is not enough(I am trying to avoid to add push all code in activity because it doesn't belong there). How to use infalte tabs.xml in view which I created by extending LinearLayout class ?

You need to inflate the .xml layout you created.

Do it like this:

public class CustomLinearLayout extends LinearLayout {

    // you need this constructor when you use the customview from code
    public CustomLinearLayout (Context context) {
        super(context);

        addView(LayoutInflater.from(context).inflate(R.layout.yourlayout, null));
    }

    // you need this constructor when the customview is used from .xml
    public CustomLinearLayout (Context context, AttributeSet attrs) {
        super(context, attrs);

        addView(LayoutInflater.from(context).inflate(R.layout.yourlayout, null));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM