android 动态设置获取控件大小,并设置宽度等于高度,或者高度等于宽度。

 

	public static void setViewWidthByHeight(View view) {
		final View mv = view;
		final ViewTreeObserver vto = mv.getViewTreeObserver();
		final ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				
//				int width = mv.getMeasuredWidth();
				int height = mv.getMeasuredHeight();
				
				android.view.ViewGroup.LayoutParams lp = mv.getLayoutParams();
				lp.width = height;
				mv.setLayoutParams(lp);

				final ViewTreeObserver vto1 = mv.getViewTreeObserver();
				vto1.removeOnPreDrawListener(this);

				return true;
			}
		};
		vto.addOnPreDrawListener(preDrawListener);
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要修改 Android HorizontalScrollView 内动态添加控件时的宽度以适应滚动条的宽度,可以使用以下代码: ```java HorizontalScrollView scrollView = findViewById(R.id.horizontal_scroll_view); LinearLayout linearLayout = findViewById(R.id.linear_layout); // 添加控件 Button button = new Button(this); linearLayout.addView(button); // 设置控件宽度 int width = 200; // 设置控件宽度为200像素 int height = LinearLayout.LayoutParams.MATCH_PARENT; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height); button.setLayoutParams(layoutParams); ``` 在上面的代码中,我们首先获取了 HorizontalScrollView 和 LinearLayout 的实例。然后我们向 LinearLayout 中动态添加了一个 Button 控件。接着,我们使用 LinearLayout.LayoutParams 来设置控件宽度高度。在这里,我们将控件宽度设置为 200 像素,并将高度设置为 MATCH_PARENT,以填充 LinearLayout 的高度。 如果你希望控件宽度与滚动条的宽度相同,可以使用以下代码来获取 HorizontalScrollView 的宽度,并将控件宽度设置为相同的值: ```java HorizontalScrollView scrollView = findViewById(R.id.horizontal_scroll_view); LinearLayout linearLayout = findViewById(R.id.linear_layout); // 添加控件 Button button = new Button(this); linearLayout.addView(button); // 设置控件宽度 int width = scrollView.getWidth(); // 设置控件宽度为 ScrollView 的宽度 int height = LinearLayout.LayoutParams.MATCH_PARENT; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, height); button.setLayoutParams(layoutParams); ``` 在这里,我们使用 getWidth() 方法获取 HorizontalScrollView 的宽度,并将控件宽度设置为相同的值。这样,控件宽度就与滚动条的宽度相同了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值