我必须在android中动态显示textviews,并且需要为每个textview编写onclick动作。我可以动态显示textviews但我没有得到 如何为每个textview编写onclick操作。请帮我解决这个问题......感谢你......
答案 0 :(得分:2)
您应该检查此代码。创建一个onclicklistener,然后使用setOnClickListener();方法
private TextView textview1, textview2;
//initialize them
OnClickListener customTextviewOnClicklistener = new OnClickListener()
{
@Override
public void onClick(View v)
{
if (v == textview1)
{
// Here your code for textview1
Log.i("Clicked Item", "textview1");
}
else if (v == textview2)
{
// Here your code for textview2
Log.i("Clicked Item", "textview2");
}
else
{
//Here your code for others
}
}
};
textview1.setOnClickListener(customTextviewOnClicklistener);
textview2.setOnClickListener(customTextviewOnClicklistener);
我希望这对你有所帮助。
答案 1 :(得分:0)
然后动态创建视图,然后添加侦听器。
TextView tv = new TextView(ActivityName.this);
tv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(ActivityName.this, "tv text: " + ((TextView) v).getText().toString()).show();
//Do whatever you want to do here.
}
});
layout.addView(tv); //layout added on the xml for example, or by an inflater.