在自定义视图构造函数中扩充活动布局



我有一个自定义按钮,其中包含自定义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
        }
    }
}

我想活动还没有膨胀,我无法从中获得观点。我能做什么?

谢谢。

代替

使用String来制作 id,app:watch_enable="edit_login_password"使用 Reference 并传递app:watch_enable="@id/edit_login_password",这将为您提供引用的 id 的整数值。

尝试通过

获取WatchingButton视图的父视图:

ViewGroup parentView = (ViewGroup)WatchingButton.this.getParent(); 
EditText et = (EditText)parentView.findViewById(idEditText);

解决了!!首先,感谢大家的回答。

首先,我已经按照Ankit Bansal所说,按@id而不是按名称引用视图。

  <com.grupogimeno.android.hoteles.widgets.WatchingButton
            android:text="Enter"
            app:watch_enable="@id/edit_login_password"/>

就像我一样,我无法在构造函数中获取父布局的视图,因为此布局尚未完全膨胀。所以我将watch_enable属性的值存储在变量中。

public WatchingButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.WatchingButton);
        this.id = attributes.getResourceId(R.styleable.WatchingButton_watch_enable, 0);
}

然后,当布局完全膨胀时onAttachedToWindow该方法在其所有视图中被调用,因此我在此处获得 EditText:

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
           EditText et = (EditText)((Activity)getContext()).findViewById(this.id);//<-- OK 
         //DO STUFF
        }
    }

最新更新