Tareq Rahman Joy Tareq Rahman Joy - 1 year ago 46
Vb.net Question

How to add event handler when creating dynamically created view in Android?

I have created all view dynamically in android studio.


RelativeLayout big = new RelativeLayout(this);
for(int i=0; i<50; i++)
RelativeLayout mini = new RelativeLayout(this);
TextView t = new TextView(this);

Now, in the sample code, I want to add events like onTouch, onClick etc. for all the 'mini' RelativeLayouts which will change the backgroundColor of the touched/clicked RelativeLayout. Can I do that in single function?

Actually, I am new in Android apps developing. I have handled events in VB.net with ease


AddHandler mini.Click, AddressOf Clicked
//sample example
Public Clicked(Byval sender As Object, e As EventArgs)
End Sub


I want to do like this in java(android), is it possible?

Answer Source

For each item you can use setOnClickListener() and setOnTouchListener():

mini.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // your action

mini.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // your action
                return true;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download