0

I want to programmatically create a spinner with margin=Xdp then add it to a LinearLayout. I think this can be achieved using LayoutParams but I got no luck.

  val spinnerLanguage = Spinner(context).apply {
            val value = Cals.dpToPx(context, 15)
            this.setPadding(value, value, value, value)
            this.adapter = SpinnerBaseChoiceSelectionAdapter(context, R.layout.simple_spinner_item, data)

            val params =  ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
            )
            params.setMargins(0, value, 0, value)
            this.rootView.layoutParams = params
        }

  spinnerHolderLayout.addView(spinnerLanguage)
  spinnerHolderLayout.addView(spinnerLanguage)
  spinnerHolderLayout.addView(spinnerLanguage)

Result got no margin between them

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
Master Zzzing
  • 524
  • 6
  • 18

1 Answers1

1

Use LayoutParams.

Look at this example

For example:

LayoutParams lp = (RelativeLayout.LayoutParams) spinnerLanguage.getLayoutParams();
            // Set spinner margin (Left Top Right Bottom)
            lp.setMargins(25,25,25,25);

            // Update parameters to spinner
            spinnerLanguage.setLayoutParams(lp);
Evyatar Cohen
  • 292
  • 1
  • 9
  • 25