I am trying to add 20 textviews and assign a onclick to dynamically added textviews. Problem is whenever i try to click any of the dynamic textiview. It always fires up click event of last added textview.
Here is my code:
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();
}
};
}
Try this:
Update:
The reason why you are clicking the last
TextViewis because it is just so big.. You are increasing the padding with each loop and when you click somewhere, it will always hit the lastViewbecause it is overlaying the others. Try aLinearLayoutand remove the padding like so:But having your problem solved.. I think a
ListViewwould suit your purpose 🙂