LinearLayoutでは、setHeight等が使えないので、android.view.ViewGroup.LayoutParamsを使う.
LinearLayout linearLayout = findViewById(R.id.LinearLayout); ViewGroup.LayoutParams layoutParams = linearLayout.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; layoutParams.width = 200; ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams)linearLayout.getLayoutParams(); marginLayoutParams.leftMargin = 8; marginLayoutParams.rightMargin = 8; marginLayoutParams.topMargin = 8; marginLayoutParams.bottomMargin = 8; linearLayout.setLayoutParams(marginLayoutParams);
単位は、pixelだそう. dip(dp)を使いたい場合は、例えば、5行目を
layoutParams.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, getResources().getDisplayMetrics());
とする. (試してない.)
この方法は、ConstraintLayoutや、ImageButton等でも使えるっぽい.
0 件のコメント:
コメントを投稿