2015-04-23 68 views
0

我有一个自定义按钮,它带有一个自定义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 
     } 
    } 
} 

我猜活动尚未膨胀,我无法从中获得的意见。我能做什么?

谢谢。

+0

请出示你得到 –

+0

只是我不能让错误EditText'et',我得到null。 –

+0

'WatchingButton扩展Button'或'WatchingButton extends View'或'WatchingButton extends ViewGroup'? –

回答

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 
     } 
    } 
1

代替使用String制作编号app:watch_enable="edit_login_password"使用Reference并通过app:watch_enable="@id/edit_login_password"这将给你的整数值引用的id。

1

尝试,因为通过WatchingButton视图获取父视图:

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