我将一个子视图添加到线性布局.儿童视图本身在Relativelayout中具有一些文本视图和图像浏览.
点击一个按钮,在LinearLayout中动态添加子视图.现在我可以添加子视图,如图所示.
http://dl.dropbox.com/u/50249620/SC20120926-031356.png
我要做的是唯一标识哪个子视图被点击以显示适当的操作.
我的代码,我在添加子视图.
点击一个按钮,在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 } }