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


91

谁能帮助我如何设置的宽度TextViewwrap_content通过代码,而不是从XML?

我正在动态创建一个TextViewin代码,因此如何wrap_content通过代码设置其宽度?

Answers:


126
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));

8
android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams
Francisco Corrales Morales 2014年

好吧,主要的区别是在第一个代码中,我们已经使用该设置创建了一个新的TextView。在第二个视图中,我们将添加到现有视图中,并且还要设置这些参数。对于中投的问题,我想你必须转换适当的类
弗朗哥

77

还有另一种方法可以达到相同的结果。如果您只需要设置一个参数,例如“ height”:

TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);

这很好。如果完成此操作,LinearLayout则没有ll.invalidate()必要。为什么?
midiwriter

1
我想我们永远不会知道
Denny

49

更改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

6
简单而正确的解决方案,因为它不会覆盖其他参数。
CoolMind

2
将我标记为可以删除,因为这要简单得多。
FrankKrumnow

2
这是最好的解决方案
pedram shabani

4

我发布了android Java base多行edittext。

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 */

1

我认为这段代码可以回答您的问题

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) 
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.