谁能帮助我如何设置的宽度TextView
要wrap_content
通过代码,而不是从XML?
我正在动态创建一个TextView
in代码,因此如何wrap_content
通过代码设置其宽度?
谁能帮助我如何设置的宽度TextView
要wrap_content
通过代码,而不是从XML?
我正在动态创建一个TextView
in代码,因此如何wrap_content
通过代码设置其宽度?
Answers:
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);
LinearLayout
则没有ll.invalidate()
必要。为什么?
更改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
我发布了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 */
android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams