[英]How to get the ID of the clicked child view added dynamically to a LinearLayout?
我正在为线性布局添加子视图。 子视图本身在Relativelayout中有一些textview和imageview。 单击按钮时,子视图会在LinearLayout中动态添加。 现在我可以添加子视图,如图所示。 http://dl.dropbox.com/u/50249620/SC20120926-031356.png我要做的是唯一标识点击了哪个子视图以显示适当的操作。 我添加子视图的代码。
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
customView1 = inflater.inflate(R.layout.people, null);
peopleName = (TextView) customView1.findViewById(R.id.peopleName);
peopleName.setText(autoComplete.getText());
customView1.setId(peopleInvitedRelativeLayout.getChildCount() + 1);
params4 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
customView1.setLayoutParams(params4);
peopleInvitedRelativeLayout.addView(customView1, params4);
}
});
任何帮助或建议将不胜感激。 谢谢。
只需在创建视图时执行以下操作,即可将自定义标记添加到任何视图
view.setTag(Object o);
然后在onClickListener中找到标签
view.getTag()
setTag(Object o)
将接受任何类型的对象,无论是字符串,int还是自定义类
编辑
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
customView1 = inflater.inflate(R.layout.people, null);
peopleName = (TextView) customView1.findViewById(R.id.peopleName);
peopleName.setText(autoComplete.getText());
customView1.setId(peopleInvitedRelativeLayout.getChildCount() + 1);
params4 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
customView1.setLayoutParams(params4);
peopleInvitedRelativeLayout.addView(customView1, params4);
//add a tag to a view and add a clicklistener to the view
customView1.setTag(someTag);
customView1.setOnClickListener(myClickListner);
}
});
clicklistener - 为它创建一个类变量
OnClickListener myClickListener = new onClickListener(){
@Override
public void onClick(View v) {
if(v.getTag() == someTag){
//do stuff
}else if(v.getTag() == otherTag){
//do something else
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.