Dynamically changing the linearlayout width or height on Android

前端 未结 4 1369
离开以前
离开以前 2020-12-08 10:28

I am trying to change linear layout or any other widget width or height dynamically but throwing exception.

My layout is:



        
相关标签:
4条回答
  • 2020-12-08 10:40

    Check this - http://smartandroidians.blogspot.com/2010/04/changing-layout-height-dynamically.html

    ll.getLayoutParams().height = 300;
    ll.getLayoutParams().width = 200;
    ll.requestLayout();
    

    This works also on event handler.

    0 讨论(0)
  • 2020-12-08 10:46

    This simple way to do your task:

    setContentView(R.id.main);    
    LinearLayout layout= (LinearLayout) findViewById(R.id.left);
    int width=60;
    int height=60;
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
    layout.setLayoutParams(parms);
    

    and another way if you want to give screen size in height and width then use below code :

    setContentView(R.id.main);    
    Display display = getWindowManager().getDefaultDisplay();
    LinearLayout layout= (LinearLayout) findViewById(R.id.left);
    int width=display.getWidth();
    int height=display.getHeight();
    LinearLayout.LayoutParams parms = new inearLayout.LayoutParams(width,height);
    layout.setLayoutParams(parms);
    

    hope use full to you.

    0 讨论(0)
  • 2020-12-08 10:52

    The problem here is that when you set the layout params the type needs to be that of the parent, in this case that is a FrameLayout. You need to do this:

    ll.setLayoutParams(new FrameLayout.LayoutParams(30,60));
    
    0 讨论(0)
  • 2020-12-08 11:00

    You can use this method inside your utils class to set height and width dynamically.

     public void setWidthAndHeight(Context context,RelativeLayout view,int width, int height) {
                    width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, context.getResources().getDisplayMetrics());//used to convert you width integer value same as dp
                    height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, context.getResources().getDisplayMetrics());
                   //note : if your layout is LinearLayout then use LinearLayout.LayoutParam
                    view.setLayoutParams(new RelativeLayout.LayoutParams(width, height));
             }
    
    0 讨论(0)
提交回复
热议问题