自定义视图构造函数

时间:2015-04-23 10:15:37

标签: android android-layout

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

我想活动还没有膨胀,我无法从中获取意见。我该怎么办?

感谢。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

通过获取WatchingButton视图的父视图来尝试:

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

答案 2 :(得分:1)

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

首先,我完成了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
        }
    }
相关问题