我有一个自定义按钮,它带有一个自定义XML字符串属性watch_enable
,它是EditText的名称。在该按钮的构造函数中,我想读取此属性,并使用该名称获取EditText。在自定义视图构造函数中膨胀活动布局
我用我的自定义按钮,如:
<EditText
android:id="@+id/edit_login_password"
android:inputType="textPassword"
android:text=""/>
<my.project.widgets.WatchingButton
android:text="Enter"
app:watch_enable="edit_login_password"/>
这是我的按钮的类:
public WatchingButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.WatchingButton);
for (int i = 0; i < attributes.getIndexCount(); i++) {
int attribute = attributes.getIndex(i);
if (attribute == R.styleable.WatchingButton_watch_enable) {
String value = attributes.getString(attribute); //<-- OK, value is edit_text_username
int idEdittext = context.getResources().getIdentifier(value, "id", context.getPackageName()); //<-- OK, I obtain the resource ID
Activity activity = (Activity) context;
EditText et = (EditText)((Activity)context).findViewById(idEditText); //<-- Error. et is null.
//DO STUFF
}
}
}
我猜活动尚未膨胀,我无法从中获得的意见。我能做什么?
谢谢。
请出示你得到 –
只是我不能让错误EditText'et',我得到null。 –
'WatchingButton扩展Button'或'WatchingButton extends View'或'WatchingButton extends ViewGroup'? –