谁能帮我如何设置的宽度TextView要wrap_content通过代码,而不是从XML?
我正在动态创建一个TextView代码,所以无论如何wrap_content通过代码设置其宽度?
Fra*_*nco 115
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)
要么
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)
Dmi*_*try 73
还有另一种方法可以达到同样的效果.如果您只需要设置一个参数,例如'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)
Pha*_*inh 46
更改TextView宽度的解决方案以包装内容.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
Run Code Online (Sandbox Code Playgroud)
Ste*_*ack 10
这篇文章的一个小更新:如果你在你的 Android 项目中使用 ktx,有一个小助手方法可以让更新 LayoutParams 更容易。
如果您只想更新例如宽度,您可以在 Kotlin 中使用以下行来完成。
tv.updateLayoutParams { width = WRAP_CONTENT }
Run Code Online (Sandbox Code Playgroud)
小智 5
我正在发布 android Java base 多行编辑文本。
EditText editText = findViewById(R.id.editText);/* edittext access */
ViewGroup.LayoutParams params = editText.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/
editText.setSingleLine(false); /* Makes it Multi line */
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94995 次 |
| 最近记录: |