[英]Adding onClick Listener on dynamically created elements not working
I am creating dynamic textview
on runtime.我正在运行时创建动态
textview
。 on adding onClick()
Listener.添加
onClick()
侦听器。 it works only on the last textview
created on runtime and not on every textview
created.它仅适用于运行时创建的最后一个
textview
,而不适用于创建的每个textview
。 This is my code:-这是我的代码:-
@Override
public void onComplete(@NonNull Task<Object> task) {
if (task.isComplete()) {
ArrayList<Document> tagLocat = (ArrayList<Document>) task.getResult();
tv=new TextView[tagLocat.size()];
for (i = 0; i < tagLocat.size(); i++) {
Document doc = tagLocat.get(i);
TextView tv1 = new TextView(MainActivity.this);
Log.i("Document", "" + doc);
notification = doc.getString("notification");
Log.i("Double", "" + notification);
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(10,10,10,10);
tv1.setLayoutParams(lparams);
tv1.setTag(i);
tv1.setId(i);
tv1.setTextSize(30);
tv1.setPadding(50, 0 ,0,0);
tv1.setText(notification);
tv[i] = tv1;
linearLayout.addView(tv[i]);
tv[i].setBackgroundColor(Color.GRAY);
tv[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tv[i].setBackgroundColor(Color.LTGRAY);
}
});
}
} else {
Log.i("Exception",task.getException().toString());
}
}
You have to add your textview in array after set onclicklistener设置 onclicklistener 后,您必须在数组中添加 textview
like喜欢
tv1.setLayoutParams(lparams);
tv1.setTag(i);
tv1.setId(i);
tv1.setTextSize(30);
tv1.setPadding(50, 0 ,0,0);
tv1.setText(notification);
tv1.setBackgroundColor(Color.GRAY);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundColor(Color.LTGRAY);
}
});
tv[i] = tv1;
linearLayout.addView(tv[i]);
Set onClickListener
before adding view .在添加 view 之前设置
onClickListener
。
Solution:-解决方案:-
for (int i = 0; i < tagLocat.size(); i++) {
// Do stuff here
tv[i].setBackgroundColor(Color.GRAY);
tv[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.setBackgroundColor(Color.LTGRAY);
}
});
tv[i] = tv1;
linearLayout.addView(tv[i]);
}
Make sure this will not toggle the color onClick()
.If you want such behaviour you need to maintain the state of TextView
.确保这不会切换颜色
onClick()
。如果你想要这样的行为,你需要保持TextView
的状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.