我正在尝试添加 20 个文本视图并将 onclick 分配给动态添加的文本视图。问题是每当我尝试单击任何动态文本视图时。它总是触发最后添加的文本视图的点击事件。
这是我的代码:
EditText s;
EditText t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout containerLayout = (RelativeLayout) findViewById(R.id.container);
for (int i = 0; i < 20; i++) {
TextView dynaText = new TextView(this);
dynaText.setText("Some text " + i);
dynaText.setTextSize(30);
dynaText.setTag("" + i);
dynaText.setOnClickListener(btnClickListener);
// Set the location of your textView.
dynaText.setPadding(0, (i * 30), 0, 0);
containerLayout.addView(dynaText);
}
}
OnClickListener btnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
RelativeLayout ll = (RelativeLayout) v.getParent();
TextView tv = (TextView) ll.getChildAt(2);
// Integer pos = (Integer) tv.getTag();
Toast.makeText(v.getContext(), "Toast " + v.getTag(),
Toast.LENGTH_SHORT).show();
}
};
}