我正在向线性布局添加 subview 。 subview 本身在 Relativelayout 中有一些 TextView 和 ImageView 。 单击按钮时, subview 会动态添加到 LinearLayout 中。现在我可以添加 subview ,如图所示。 http://dl.dropbox.com/u/50249620/SC20120926-031356.png 我必须做的是唯一地标识已单击哪个 subview 以显示适当的操作。 我添加 subview 的代码。
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 时简单地通过执行以下操作将自定义标签添加到任何 View
view.setTag(Object o);
然后在 onClickListener 中找到标签
view.getTag()
setTag(Object o)
将接受任何类型的对象,无论是字符串、整数还是自定义类
编辑
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
}
}
关于android - 如何获取动态添加到 LinearLayout 中的点击 subview 的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12591590/