简体   繁体   中英

How to inflate xml-layout into child View

I'm trying to inflate xml-layout into custom View-class, which is then placed into LinearLayout in actual software. After some Googling I managed to create custom class which inflates the layout by using following class:

    public class LitteringView extends RelativeLayout
{

    public LitteringView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        View.inflate(context, R.layout.littering_layout, this);

    }


    public LitteringView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // TODO Auto-generated method stub
         for(int i = 0 ; i < getChildCount() ; i++){
             getChildAt(i).layout(l, t, r, b);
         }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO Auto-generated method stub
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }





}

Now it definitely inflates when I add it to the linearlayout:

layout.addView(new LitteringView(getActivity()));

Problem is that it takes the whole screen while the screen should be divided equally between LinearLayout's three children. Other Views are also created dynamically. How I can prevent it from taking the whole space?

I'm trying to create one custom View/class and package its functions inside it which I then could easily add to the parent layout (in this case the LinearLayout) while wanting to utilize xml to define the layout of the View.

You need to use 'weight' for your views. A simple example for this:

Layout.LayoutParams params = new LinearLayout.LayoutParams(width, height, weight);

You need to optimize it for your case. Give all your views a weight value equally(eg: 1 for all of them) and they should share the view.

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