我正在为线性布局添加子视图。子视图本身在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);
}
});
任何帮助或建议将不胜感激。感谢。
答案 0 :(得分:13)
只需在创建视图时执行以下操作,即可将自定义标记添加到任何视图
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
}
}