当我在Android中动态构建View
时,我必须通过调用将其添加到“父”ViewGroup
myLinearLayout.addView(myView);
我知道我可以监督ViewGroup
,通过优秀的onHierarchyChangeListener添加任何孩子,但在我的情况下,我需要在View
本身的反馈。因此我的问题是:
有什么像View.onAddedToParent()
回调或我可以建立的听众?
为了使事情变得非常清楚:我希望视图能够自己处理所有事情,我知道我可以在“父”中捕获事件,然后通知视图有关事情,但这不是必需的。我只能改变观点
编辑:我刚刚找到onAttachStateChangeListener,它似乎适用于大多数情况,但我想知道这是否真的是正确的解决方案。我想View
也可以从一个ViewGroup
传递到另一个public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Log.d("CustomView", "onAttachedToWindow called for " + getId());
Toast.makeText(getContext(), "added", 1000).show();
}
}
而不会脱离窗户。所以即使我愿意也不会收到活动。如果你有洞察力,请你详细说明一下吗?
提前致谢
您可以在其onAttachedToWindow中创建自定义视图并执行您的操作
@Override
protected void onAttachedToWindow() {
// TODO Auto-generated method stub
super.onAttachedToWindow();
if(((View)getParent()).getId()== R.id.relativelayout2)
{
Log.d("CustomView","onAttachedToWindow called for " + getId());
Toast.makeText(context, "added", 1000).show();
}
}
如果要确保将自定义视图添加到所需的正确视图组中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setOnHierarchyChangeListener(new OnHierarchyChangeListener() {
@Override
public void onChildViewRemoved(View parent, View child) {
Log.e("View","removed");
if(child instanceof CustomButton){
CustomButton button = (CustomButton)child;
button.addListener();
}
}
@Override
public void onChildViewAdded(View parent, View child) {
Log.e("View","added");
if(child instanceof CustomButton){
CustomButton button = (CustomButton)child;
button.addListener();
}
}
});
for(int i = 0; i < 10; ++i){
CustomButton view = new CustomButton(this);
view.setText("Button "+i);
layout.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
layout.removeViewAt(layout.getChildCount()-1);
}
});
}
setContentView(layout);
}
在我看来,你想要这样;
CreateViews;
public interface OnAddedListener {
public void addListener();
}
监听;
public class CustomButton extends Button implements OnAddedListener{
public CustomButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
public void addListener() {
Log.e("","In button add listener");
}
}
CustomButton类;
removeView()