Android EditText 宽度设置方法:像素、布局参数、百分比 - 详细教程
在Android中,可以使用以下方式设置EditText的宽度:
- 使用像素值设置宽度:
int widthInPixels = 200; // 设置宽度为200像素
editText.setWidth(widthInPixels);
- 使用布局参数设置宽度:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT); // 设置宽度为200像素,高度为包裹内容
editText.setLayoutParams(layoutParams);
- 使用百分比设置宽度(需要在布局文件中使用ConstraintLayout或LinearLayout作为父布局):
float widthPercentage = 0.5f; // 设置宽度为父布局宽度的50%
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) editText.getLayoutParams();
layoutParams.width = (int) (parentLayout.getWidth() * widthPercentage);
editText.setLayoutParams(layoutParams);
注意:在使用百分比设置宽度时,需要获取父布局的宽度(parentLayout.getWidth())来计算目标宽度。
原文地址: http://www.cveoy.top/t/topic/pswN 著作权归作者所有。请勿转载和采集!