Is it possible to change the layout width and height in Android at run time?

后端 未结 5 1823
不思量自难忘°
不思量自难忘° 2021-01-01 16:22

I have two relative layouts. Both have width of fill parent and height of 100 dip. My requirement is when I click the first layout it should shrink to 50dip height and the o

相关标签:
5条回答
  • 2021-01-01 17:04

    Hi you can change the width and height of your layout using this code.

    RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(width,height);
    RelativeLayout layout1 = (RelativeLayout) findViewById(R.id.layout1);
    lauout1.setLayoutParams(parms);
    
    0 讨论(0)
  • 2021-01-01 17:12

    These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

    So basically, if you are adding a view to another, you MUST set the LayoutParams of the view to the LayoutParams type that the parent uses or you will get a runtime error.

    0 讨论(0)
  • 2021-01-01 17:13

    In onClick Listener add this code.

    Button button = (Button) findViewById(view.getId());
    LinearLayout rLGreen = ((LinearLayout) button.getParent());
    rLGreen.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    

    It will work.

    0 讨论(0)
  • 2021-01-01 17:23

    Remember that the LayoutParams are use by the Parent(viewgroup of parent) in order to determine how to layout this View.

    Thus for example if you have the following

    LinearLayout
        RelativeLayout1
        RelativeLayout2
    

    And you want to change the width or height of the RelativeLayout1 or RelativeLayout2, then you need to do something like this.

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 200);
    //Get handle to RelativeLayout1 assuming it is R1, you would call
    R1.setLayoutParams(lp);
    

    You would need to do the same to change RelativeLayout2's LayoutParams also.

    Is is easy to forget the hierarchy, and to assume that you need to set the layout of the child, but it is the parent that determines what attributes are supported (eg. Alignment, or gravity etc..)

    Hope this helps. It has burned me a few times....

    0 讨论(0)
  • 2021-01-01 17:24

    Are you using the correct LayoutParams class for your particular view? Try using LinearLayout.LayoutParams.

    0 讨论(0)
提交回复
热议问题