Bất cứ ai có thể giúp tôi cách đặt chiều rộng của TextViewwrap_content mã đến thông qua mã và không từ XML?
Tôi đang tạo động một TextViewmã trong mã, vậy có cách nào để đặt chiều rộng của nó thành wrap_contentthông qua mã không?
Bất cứ ai có thể giúp tôi cách đặt chiều rộng của TextViewwrap_content mã đến thông qua mã và không từ XML?
Tôi đang tạo động một TextViewmã trong mã, vậy có cách nào để đặt chiều rộng của nó thành wrap_contentthông qua mã không?
Câu trả lời:
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Đối với các bố cục khác nhau như ConstraintLayoutvà các bố cục khác, chúng có các bố cục riêng LayoutParams, như vậy:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
hoặc là
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Có một cách khác để đạt được kết quả tương tự. Trong trường hợp bạn chỉ cần đặt một tham số, ví dụ: 'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
LinearLayoutnó có vẻ như không ll.invalidate()cần thiết. Tại sao?
Giải pháp để thay đổi TextViewchiều rộng để bọc nội dung .
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
Tôi đang đăng văn bản chỉnh sửa nhiều dòng cơ sở 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 */
android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams