我试图以编程方式设置自定义 EditText 组件的高度,但没有成功。我有一个继承自 EditText 的自定义类,用于设置自定义字体。 我想更新 EditText 的高度和填充,但我的所有 Intent 都没有更新它。只有当我在 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);
}
}
我见过 similar post ,使用相同的方法,但我无法使其工作。
更新:
鉴于快速响应,请在下面找到对场景的澄清:
- 我有很多 EditText,它们是动态添加到 Activity 布局中的。我需要从自定义控件而不是 Activity 中执行此操作。我正在 EditText 中寻找正确的事件(如 onDraw、onPredraw 等),以便读取和设置布局参数。如果您发现要覆盖的正确事件,请告诉我。再次感谢!
- getLayoutParams 在 View (EditText) 的构造函数中返回 null。因此,我认为当布局被实例化时,解决方案可能会解决正确的事件。
- 到目前为止,我已经尝试并阅读了很多事件,例如 onDraw、onLayout、onFinishInflate 等。但是参数被忽略,或者抛出异常。
感谢当前的答案,感谢 TIA 的任何进一步答案!
米尔顿。
最佳答案
尝试从包含 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"
/>
MyActivity.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);
}
像魅力一样工作!
关于android - 如何以编程方式设置编辑文本的布局高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15835684/