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

And*_*era 81 android textview

谁能帮我如何设置的宽度TextViewwrap_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)

  • `android.view.ViewGroup $ LayoutParams无法强制转换为android.widget.LinearLayout $ LayoutParams` (8认同)

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)

  • 我想我们永远不会知道 (3认同)

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)

  • 简单而正确的解决方案,因为它不会覆盖其他参数. (5认同)
  • 将我标记为要删除,因为这要简单得多。 (2认同)
  • 这是最好的解决方案 (2认同)

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)