Tareq Rahman Joy Tareq Rahman Joy - 3 months ago 22
Vb.net Question

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

I have created all view dynamically in android studio.

Ex:

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


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

(Ex.

AddHandler mini.Click, AddressOf Clicked
//sample example
Public Clicked(Byval sender As Object, e As EventArgs)
sender.BackColor=Color.Black
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() {
            @Override
            public void onClick(View view) {
                // your action
            }
        });

mini.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                // your action
                return true;
            }
        });