android - 通过代码将 TextView 的宽度设置为 wrap_content

谁能帮助我如何通过代码而不是 XML 将 TextView 的宽度设置为 wrap_content

我在代码中动态创建一个TextView,那么有没有办法通过代码将其宽度设置为wrap_content

最佳答案

TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

对于ConstraintLayout等不同的布局,它们都有自己的LayoutParams,像这样:

pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

https://stackoverflow.com/questions/4854492/

相关文章:

android - Kotlin 错误 : Could not find org. jetbrain

java - Android:如何以编程方式启用/禁用 Wifi 或 Internet 连接

android - Android PopupWindow Activity 时背景模糊或变暗

android - 什么是 CSS 的 dp(密度独立像素)单位?

android - 如何使用它自己的操作按钮关闭 Snackbar?

android - 何时清除 Android 中的缓存目录?

android - 如何将 Activity 带到前台(堆栈顶部)?

android - 如何使用 Android Studio 查看共享首选项文件?

android - NoSuchFieldError : No static field listV

android - 在 AsyncTask 中获取上下文