ViewGroup.addView()后导致layout_height等属性失效原因

本文探讨了在Android开发中,使用ViewGroup.addView()添加子视图时,为何layout_height等属性可能会失效的问题。通过分析源码,揭示了Inflate方法的不同参数如何影响布局参数设置的过程。
部署运行你感兴趣的模型镜像

首先看一下addview源码

public void addView(View child) {
        addView(child, -1);
}


public void addView(View child, int index) {
        LayoutParams params = child.getLayoutParams();
        if (params == null) {
            params = generateDefaultLayoutParams();
            if (params == null) {
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
            }
        }
        addView(child, index, params);
}
解决方案:     1.当addView方法完成之后,重新设置子控件vChild的LayoutParams属性即可。
调用inflate (int resource, ViewGroup root, boolean attachToRoot) 方法。将第二个参数设为待加入布局的父布局,第三个参数为false


Inflate(resId , null ) 只创建temp ,返回temp

Inflate(resId , parent, false )创建temp,然后执行temp.setLayoutParams(params);返回temp

Inflate(resId , parent, true ) 创建temp,然后执行root.addView(temp, params);最后返回root

更多参见:http://blog.youkuaiyun.com/lmj623565791/article/details/38171465

您可能感兴趣的与本文相关的镜像

Qwen3-8B

Qwen3-8B

文本生成
Qwen3

Qwen3 是 Qwen 系列中的最新一代大型语言模型,提供了一整套密集型和专家混合(MoE)模型。基于广泛的训练,Qwen3 在推理、指令执行、代理能力和多语言支持方面取得了突破性进展

<FrameLayout android:id="@+id/switch_video_map" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/white"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:text="捡球车遥控面板" android:textColor="#263238" android:textSize="20sp" android:textStyle="bold"></TextView> </RelativeLayout> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:cardCornerRadius="8dp" android:layout_marginBottom="16dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp"> </androidx.cardview.widget.CardView> </LinearLayout> <com.skydroid.fpvplayer.FPVWidget android:id="@+id/fpvWidget" android:layout_width="190dp" android:layout_height="100dp" android:layout_gravity="bottom|start" android:background="@color/black"/> </FrameLayout> fpvWidget = findViewById(R.id.fpvWidget); mapWidget = findViewById(R.id.map); switchVideoMapLayout = findViewById(R.id.switch_video_map); mapWidget.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFullVideo) { switchVideoMap(); } } }); fpvWidget.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isFullVideo) { switchVideoMap(); } } }); private boolean isFullVideo = false; private void switchVideoMap() { if (isFullVideo) { // 设置交换图层后的宽高 FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams) fpvWidget.getLayoutParams(); fpvLayoutParams.width = PxUtils.dp2px(this, 190); fpvLayoutParams.height = PxUtils.dp2px(this, 100); fpvLayoutParams.gravity = Gravity.BOTTOM | Gravity.START; fpvWidget.setLayoutParams(fpvLayoutParams); FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams) mapWidget.getLayoutParams(); mapLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; mapLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; mapWidget.setLayoutParams(mapLayoutParams); // 交换图层 switchVideoMapLayout.removeView(fpvWidget); switchVideoMapLayout.addView(fpvWidget); isFullVideo = false; } else { // 设置交换图层后的宽高 FrameLayout.LayoutParams fpvLayoutParams = (FrameLayout.LayoutParams) fpvWidget.getLayoutParams(); fpvLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; fpvLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; fpvWidget.setLayoutParams(fpvLayoutParams); FrameLayout.LayoutParams mapLayoutParams = (FrameLayout.LayoutParams) mapWidget.getLayoutParams(); mapLayoutParams.width = PxUtils.dp2px(this, 190); mapLayoutParams.height = PxUtils.dp2px(this, 100); mapLayoutParams.gravity = Gravity.BOTTOM | Gravity.START; mapWidget.setLayoutParams(mapLayoutParams); // 交换图层 switchVideoMapLayout.removeView(mapWidget); switchVideoMapLayout.addView(mapWidget); isFullVideo = true; } } 这是我的一个安卓代码,点击map和fpvWidget,可以实现俩个界面自动切换显示,但是我现在发现从fpvWidget切换回map的时候,map里面CardView里面的数据右边的一半没有显示?请帮我分析是怎么回事?应该怎么修改?
最新发布
11-25
我现在的逻辑是,对于单个view生成固定大小的色块覆盖然后使用addView(view,sourceindex)的方式添加并把原来的sourcevview设置为gone,但是如果parent是约束布局的时候就会失效,所以需要get具体位置然后add,目前代码如下private fun createSingleViewSkeleton(view: View, config: SkeletonConfig): View { return when (view) { is ImageView -> { Log.e("createSingleView","pic.width=${view.width},pic.height=${view.height}") ViewUtils.createRoundedRectDrawable( view.context, view.width, view.height, config.cornerRadius, config.maskColor ) } is TextView -> ViewUtils.createTextSkeleton( view.context, view.width, view.height, config.cornerRadius, config.maskColor ) else -> ViewUtils.createRoundedRectDrawable( view.context, view.width, view.height, config.cornerRadius, config.maskColor ) } },private fun createAutoSkeleton(view: View, config: SkeletonConfig): Skeleton { val skeletonView = when (view) { is ViewGroup -> createViewGroupSkeleton(view, config) else -> createSingleViewSkeleton(view, config) } return object : Skeleton { override val view = skeletonView override fun show(parent: ViewGroup, x: Float, y: Float) { val oldParent = skeletonView.parent as? ViewGroup oldParent?.removeView(skeletonView) parent.addView(skeletonView) skeletonView.x = x skeletonView.y = y } override fun destroy() { (skeletonView.parent as? ViewGroup)?.removeView(skeletonView) Log.e("SkeletonFactory", "destroy called") } } } private fun createViewGroupSkeleton(group: ViewGroup, config: SkeletonConfig): FrameLayout { val context = group.context val skeletonContainer = FrameLayout(context) // 测量整个 group 以确保 layout 已完成 if (group.width == 0 || group.height == 0) { group.measure( View.MeasureSpec.makeMeasureSpec(group.layoutParams.width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(group.layoutParams.height, View.MeasureSpec.EXACTLY) ) group.layout(group.left, group.top, group.right, group.bottom) } // 获取父容器在窗口中的位置(用于坐标转换) val parentLocation = IntArray(2) group.getLocationInWindow(parentLocation) val parentX = parentLocation[0] val parentY = parentLocation[1] for (i in 0 until group.childCount) { val child = group.getChildAt(i) // 跳过占位视图如 Space if (child is Space) continue // 确保子 view 已测量 if (child.measuredWidth == 0 || child.measuredHeight == 0) { val widthSpec = if (child.layoutParams.width >= 0) View.MeasureSpec.makeMeasureSpec(child.layoutParams.width, View.MeasureSpec.EXACTLY) else View.MeasureSpec.makeMeasureSpec(group.measuredWidth, View.MeasureSpec.AT_MOST) val heightSpec = if (child.layoutParams.height >= 0) View.MeasureSpec.makeMeasureSpec(child.layoutParams.height, View.MeasureSpec.EXACTLY) else View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) child.measure(widthSpec, heightSpec) } // 创建骨架色块 val childSkeleton = createAutoSkeleton(child, config).view // 获取子 view 在屏幕中的绝对坐标 val childLocation = IntArray(2) child.getLocationInWindow(childLocation) val childGlobalLeft = childLocation[0] val childGlobalTop = childLocation[1] // 计算相对于 skeletonContainer 的左上角偏移(因为 skeletonContainer 将作为 overlay 显示在同一位置) val leftInParent = childGlobalLeft - parentX val topInParent = childGlobalTop - parentY // 设置 FrameLayout.LayoutParams 并用 margin 定位 val lp = FrameLayout.LayoutParams(child.measuredWidth, child.measuredHeight) lp.leftMargin = leftInParent lp.topMargin = topInParent skeletonContainer.addView(childSkeleton, lp) } return skeletonContainer }fun replace(sourceView: View, targetView2: View): Boolean { if(sourceView is ImageView) { // 1. 检查父容器 sourceParentView = sourceView.parent as? ViewGroup ?: run { Log.e(TAG, "原视图没有父容器,无法替换") return false } val index = sourceParentView!!.indexOfChild(sourceView) // ✅ 获取原 view 的真实宽高(已 layout 完成) val finalWidth = sourceView.width val finalHeight = sourceView.height if (finalWidth <= 0 || finalHeight <= 0) { Log.w(TAG, "原视图尺寸为 0,可能尚未 layout,等待下一帧...") targetView2.post { replace(sourceView, targetView2) } return false } // ✅ ★ 所有 targetView2 都走“精确匹配”逻辑(含色块、ImageView、自定义 View) targetView2.measure( View.MeasureSpec.makeMeasureSpec(finalWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(finalHeight, View.MeasureSpec.EXACTLY) ) // 布局自身 targetView2.layout(0, 0, targetView2.measuredWidth, targetView2.measuredHeight) Log.d(TAG, "目标视图已设置尺寸: ${targetView2.measuredWidth}x${targetView2.measuredHeight}") // ✅ 配置 layoutParams 并保持 margin 和 translation configureLayoutParams(sourceView, targetView2, targetView2.measuredWidth, targetView2.measuredHeight) // ✅ 插入到原位置 sourceParentView!!.addView(targetView2, index) sourceView.visibility = View.GONE currentView = targetView2 targetView = targetView2 Log.d(TAG, "视图替换完成,索引: $index") return true }else{ val parent = sourceView.parent as? ViewGroup ?: return false val index = parent.indexOfChild(sourceView) // 隐藏原始 view sourceView.visibility = View.GONE // 使用原 layoutParams 测量新视图 val lp = sourceView.layoutParams targetView2.layoutParams = ViewGroup.LayoutParams(lp.width, lp.height) // 确保父容器宽高有效 val parentWidth = parent.width val parentHeight = parent.height val widthSpec = when (lp.width) { ViewGroup.LayoutParams.MATCH_PARENT -> View.MeasureSpec.makeMeasureSpec(parentWidth, View.MeasureSpec.EXACTLY) ViewGroup.LayoutParams.WRAP_CONTENT -> View.MeasureSpec.makeMeasureSpec(parentWidth, View.MeasureSpec.AT_MOST) else -> View.MeasureSpec.makeMeasureSpec(lp.width, View.MeasureSpec.EXACTLY) } val heightSpec = when (lp.height) { ViewGroup.LayoutParams.MATCH_PARENT -> View.MeasureSpec.makeMeasureSpec(parentHeight, View.MeasureSpec.EXACTLY) ViewGroup.LayoutParams.WRAP_CONTENT -> View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.AT_MOST) else -> View.MeasureSpec.makeMeasureSpec(lp.height, View.MeasureSpec.EXACTLY) } // 测量和布局 targetView2.measure(widthSpec, heightSpec) targetView2.layout( sourceView.left, sourceView.top, sourceView.left + targetView2.measuredWidth, sourceView.top + targetView2.measuredHeight ) // 插入父容器 parent.addView(targetView2, index) currentView = targetView2 return true } return false } private fun configureLayoutParams(sourceView: View, targetView: View, width: Int, height: Int) { val layoutParams = when (val lp = sourceView.layoutParams) { is ViewGroup.MarginLayoutParams -> { ViewGroup.MarginLayoutParams(width, height).apply { leftMargin = lp.leftMargin topMargin = lp.topMargin rightMargin = lp.rightMargin bottomMargin = lp.bottomMargin } } else -> { ViewGroup.LayoutParams(width, height) } } targetView.layoutParams = layoutParams targetView.translationX = sourceView.translationX targetView.translationY = sourceView.translationY }应该怎么修改呢
09-20
private void handleCodeResult(final QrCodeResult result) { if ((null == mActivity) || mbPause) { CameraLog.d(TAG, () -> "handleCodeResult activity is destroyed"); return; } if (result.isInterrupt()) { return; } QrCodeResult.Type type = result.getType(); String content = result.getContent(); if (type == QrCodeResult.Type.NONE) { searchCode(content); } else if (type == QrCodeResult.Type.WIFI) { Intent intent = new Intent(ACTION_WIFI_SHARE); intent.setPackage(WIRELESS_PACKAGE_NAME); intent.putExtra(EXTRA_WIFI_RAWRESULT, content); try { mActivity.startActivity(intent); reportJumpQrCode(getScreenBrightness(), 1, EventConstant.QRCodeType.TYPE_JUMP_WIFI); } catch (Exception e) { CameraLog.e(TAG, "handleCodeResult, innerHandleCodeResult e: " + e); searchCode(content); } } else { searchCode(content); } } private float getScreenBrightness() { return Settings.System.getInt(mActivity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, (int) (mMaxScreenBrightness * SETTING_BRIGHTNESS_SCALE)); } private boolean searchCode(String content) { if (null == mActivity) { return false; } boolean openUri = false; if (Patterns.WEB_URL.matcher(content).matches() || URLUtil.isValidUrl(content)) { Uri uri = Uri.parse(Util.normalizeUrl(content)); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { mActivity.startActivity(intent); openUri = true; reportJumpQrCode(getScreenBrightness(), 1, EventConstant.QRCodeType.TYPE_JUMP_HTTP); } catch (Exception e) { CameraLog.e(TAG, "searchCode e: " + e); mbClickJump = false; } } if (!openUri) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, content); if (Util.isAppInstalled(getContext(), BROWSER_HEYTAP_PACKAGE_NAME)) { intent.setPackage(BROWSER_HEYTAP_PACKAGE_NAME); } else if (!Util.isAppInstalled(getContext(), BROWSER_CHROME_PACKAGE_NAME)) { intent.setPackage(BROWSER_PACKAGE_NAME); } intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { mActivity.startActivity(intent); openUri = true; reportJumpQrCode(getScreenBrightness(), 1, EventConstant.QRCodeType.TYPE_JUMP_TEXT); } catch (Exception e) { CameraLog.e(TAG, "searchCode e: " + e); mbClickJump = false; } } return openUri; } private Context getContext() { if (null != mActivity) { return mActivity.getApplicationContext(); } return null; } public void addQrCodeJumpView(ViewGroup parentView, ViewGroup previewFrame, RelativeLayout controlPanelLayout) { if ((null == parentView) || (null == mQrCodeJumpView)) { return; } mCameraQrCodeView = previewFrame.findViewById(R.id.qrcode_view); if (null == mCameraQrCodeView) { mCameraQrCodeView = (CameraQrCodeView) mActivity.getLayoutInflater() .inflate(R.layout.view_stub_qrcode_view, previewFrame) .findViewById(R.id.qrcode_view); } if (!mbPause) { mCameraQrCodeView.onResume(); } parentView.removeView(mQrCodeJumpView); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, Optional.ofNullable(getContext()).map( (c) -> c.getResources().getDimensionPixelSize(R.dimen.ai_notice_view_height)) .orElse(Util.dp2px(AI_NOTICE_VIEW_HEIGHT))); layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL); layoutParams.addRule(RelativeLayout.ABOVE, controlPanelLayout.getId()); int previewTop = previewFrame.getTop(); int previewHeight = previewFrame.getHeight(); int topMargin = mActivity.getResources().getDimensionPixelSize( ResDecisionManager.getConvertId(R.dimen.pi_ultra_wide_hint_layout_margin_top)); layoutParams.bottomMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.qr_code_vertical_margin_bottom); parentView.addView(mQrCodeJumpView, layoutParams); mQrCodeJumpView.init(topMargin, previewTop, previewHeight, 0); mQrCodeJumpView.setVisibility(View.GONE); View next = mQrCodeJumpView.findViewById(R.id.camera_qr_code_hint_next); boolean rtl = mQrCodeJumpView.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL; next.setRotation(rtl ? CommonConstant.Orientation.ORIENTATION_180 : CommonConstant.Orientation.ORIENTATION_0); } public void showQrCodeJumpView(boolean animation) { if ((null == mQrCodeJumpView) || (null == mActivity) || (null == mQrCodeScanResult) || mbPause) { return; } if (null != mQrCodeJumpView.getParent()) { mQrCodeJumpView.setOrientation(mOrientation); if (mQrCodeJumpView.isVisibile()) { mQrCodeJumpView.startHideDelay(); } else { mQrCodeJumpView.showQrCodeJumpView(true, animation); ReportThread.postEvent(ReportThread.MSG_EVENT_FUNCTION_SCAN_QR_CODE, () -> DcsReporter.get206Instance().reportScanQRCode(getScreenBrightness(), 1)); } } }你看一下这些代码里有没有问题原因
09-12
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值