Search code examples
androidandroid-layout

Android Widget/View LayoutParams how to get them?


I'm using Android Giraffe and I want to get the LayoutParams from a button, then change one of the values, then set the new params, like so:

//get the current params
LayoutParams params = button.getLayoutParams();
//change something in the params
//set the button with the new params
button.setLayoutParams(params);

However, "LayoutParams" is not an option by itself. The options are specific to a view. For example:

ConstraintLayout.LayoutParams
ViewGroup.LayoutParams
ActionBar.LayoutParams
etc...

Is one of these options supposed to work for just a Button? There is no Button.LayoutParams. How do accomplish what I'm trying to do?


Solution

  • I figured it out. You just have to typecast the LayoutParams to the type of layout that the widget is within:

    //get the current params and typecast to the parent layout type
    ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) button.getLayoutParams();
    //change something in the params
    params.setMargins(0, 0, 0, 200);
    //set the button with the new params
    button.setLayoutParams(params);