1

我正在尝试以编程方式设置自定义 EditText 组件的高度,但没有成功。我有一个从 EditText 继承的自定义类来设置自定义字体。我想更新 EditText 的高度和填充,但我所有的意图都没有更新它。只有当我在 XML 文件中设置高度时,高度才会更新。

这里是 XML:

<example.ui.customcontrols.CustomEditText
    android:id="@+id/txtUsername"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dip"
    android:layout_marginTop="2dip"
    android:inputType="text"
    android:singleLine="true" />

这里是自定义EditText的代码:

public class CustomEditText extends EditText {
    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.init();
    }
    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init();
    }
    public CustomEditText(Context context) {
        super(context);
        this.init();
    }
    public void init() {
        UIHelper.setTypeface(this);
        this.setTextSize(17);

        // This is not working.
        this.setLayoutParams(newLayoutParams(LayoutParams.FILL_PARENT, 10));
        this.setPadding(this.getPaddingLeft(), 0, this.getPaddingRight(), 0);
    }
}

我看过一个类似的帖子,使用相同,但我无法使其工作。

更新:

鉴于快速响应,请在下面找到对场景的说明:

  1. 我有很多 EditText,它们是在活动布局中动态添加的。我需要从自定义控件而不是活动中执行此操作。我正在 EditText 中寻找正确的事件(如 onDraw、onPredraw 等),以便读取和设置布局参数。如果您找到要覆盖的适当事件,请告诉我。再次感谢!
  2. getLayoutParams 在视图 (EditText) 的构造函数中返回 null。所以,我认为当布局被实例化时,解决方案可能会解决正确的事件。
  3. 到目前为止,我已经尝试并阅读了很多事件,例如 onDraw、onLayout、onFinishInflate 等。但是参数被忽略或引发异常。

Tks 获取当前答案,TIA 获取任何进一步的答案!

弥尔顿。

4

2 回答 2

1

尝试从包含 CustomEditText 的布局中执行此操作。例如:

主要的.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
    >
<com.example.untitled1.CustomEditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, MyActivity"
        android:id="@+id/et"
        />

我的活动.java

public class MyActivity extends Activity {

private CustomEditText et;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    et= (CustomEditText) findViewById(R.id.et);
    ViewGroup.LayoutParams lp = et.getLayoutParams();
    lp.width = 100;
    lp.height = 100;
    et.setLayoutParams(lp);
}

}

像魅力一样工作!

于 2013-04-05T13:58:48.160 回答
0
   LayoutParams params = layout.getLayoutParams();
 // Changes the height and width to the specified *pixels*
 params.height = 100;
 params.width = 100;
于 2013-04-05T13:55:44.957 回答