在Android中,可以使用以下方式设置EditText的宽度:

  1. 使用像素值设置宽度:
int widthInPixels = 200; // 设置宽度为200像素
editText.setWidth(widthInPixels);
  1. 使用布局参数设置宽度:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT); // 设置宽度为200像素,高度为包裹内容
editText.setLayoutParams(layoutParams);
  1. 使用百分比设置宽度(需要在布局文件中使用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 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录