1

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Tareq Joy
  • 342
  • 3
  • 12

2 Answers2

1

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;
            }
        });
GVillani82
  • 17,196
  • 30
  • 105
  • 172
0

First of all, you're recreating RelativeLayout object mini and so there'll just be only one object always. And also, you need to bind them with different RelativeLayout view elements using their individual ids.

You can then proceed on to create and attach event listeners and handlers. The code is very basic for that and since you don't even know to go along with that, I'd suggest you to first go through the basics of Android App Development.

Aakash Verma
  • 3,705
  • 5
  • 29
  • 66
  • Thanks for your reply. If you give me some sample codes, it will really help me! – Tareq Joy Jul 02 '17 at 18:44
  • [This](https://stackoverflow.com/questions/10673628/implementing-onclicklistener-for-dynamically-created-buttons-in-android) is exactly what you are looking for :) Please accept my answer if you think it helped you – Aakash Verma Jul 02 '17 at 18:46
  • The object that you're creating of RelativeLayout needs to be set to the id of some view. – Aakash Verma Jul 02 '17 at 18:47