Setting width to wrap_content for TextView through code

Can anyone help me how to set the width of TextView to wrap_content through code and not from XML?

I am dynamically creating a TextView in code ,so is there anyway to how to set its width to wrap_content through code?

132531 次浏览
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));

还有另外一种方法可以达到同样的效果,如果你只需要设置一个参数,例如“ height”:

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

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

I think this code answer your question

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);

我张贴 android Java 基础多行编辑文本。

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

A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.

如果你想更新,例如只更新宽度,你可以在 Kotlin 使用下面的行。

tv.updateLayoutParams { width = WRAP_CONTENT }