How to inflate XML-Layout-File correctly inside Custom ViewGroup?

后端 未结 6 1667
悲&欢浪女
悲&欢浪女 2020-12-07 16:13

I want to inflate a XML-Layout-File in a custom ViewGroup Class, my Problem is that it produces just a empty screen. Doing the same in the Activity Class works fine. Here i

6条回答
  •  猫巷女王i
    2020-12-07 17:10

    Overriding onLayout is necessary.when you create a object of ViewNumber(ViewGroup vg = new ViewNumber(this)),it is like inflating xml below:

    
    

    so if you don't override onLayout,ViewNumber's onLayout can't find any child,then it will be blank.

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
    

    after overriding,it will use the onLayout method of ViewNumber's parent, if your codes is:

    public class ViewNumber extends RelativeLayout {
    ...
    private void initView(Context context){
            View.inflate(context, R.layout.shownumberlayout,this); 
        }
    ...
    }
    

    then it's like inflating xml below

      
      
    

    there is one more RelativeLayout.To sovle this,you may write:

    public class ViewNumber extends RelativeLayout {
    ...
    private void initView(Context context){
            inflater.inflate( R.layout.login_view_layout, null );
                  //change (..,this) to (..,null)
        }
    ...
    }
    

    However, something unexpected will happen.android:layout_xxx=".."of your xml file may change(this is why your text is put in the top left corner). To learn more and a better solution,you can see talkol' answer and fgeorgiew's comment under it :)

提交回复
热议问题