0

I am using this code in kotlin to update the layout_weight of a linear_layout as an indication. When the button is pressed though, the layout weight doesn't change.

This will eventually be a fun app using random updates but for now I want to make sure that the code works. predWt is the button id physWt is the linearlayout id (currently set with weight 0.3)

        predWt.setOnClickListener {
        physWt.layoutParams.apply {
            (this as LinearLayout.LayoutParams).weight = 0.85f }
        }

The app launches OK and when the button is pressed the layout_weight of the linearlayout should update to 0.85f from 0.3 but does not. There are no error messages generated.

edwind
  • 3
  • 3

1 Answers1

0

You need to call setLayoutParams to let the change take effect:

    predWt.setOnClickListener {
    physWt.layoutParams.apply {
        (this as LinearLayout.LayoutParams).weight = 0.85f }
        physWt.setLayoutParams(this)
    }

The reason for this is that the view and its parent view does not know you modified the layout params, by setting it again, View.requestLayout() is called for you

ssynhtn
  • 1,307
  • 12
  • 18
  • Using the physWt.setLayoutParams(this) as suggested produced an error of wrong inferred type but using physWt.requestLayout() worked. I only mention this for anyone with a similar problem. If I misunderstood your answer, my apologies. – edwind Jul 26 '19 at 09:39
  • Any improvements would be gratefully received. I am new to coding and appreciate all help. Thank you for your advice. – edwind Jul 29 '19 at 08:33