Is there a way to distinguish between TextViews or any other Views having same ID's inflated multiple times from a single xml file

StackOverflow https://stackoverflow.com/questions/8510076

Frage

I hope I get an answer to my question this time, I already posted a question on this but I guess people overlooked it since it was not put properly, here is a link to my previous question How do I know the ID's of views if I am inflating a view multiple times in the same parent on button click? I am inflating child.xml which contains a TableLayout with 3 LinearLayouts which again contain TextView's in my main Activity on button click event, the user can add as many views as he wants.

But I am confused as of how to collect the data from those textviews or setOnClickListeners to them since different views share the TextView's which same Id.

People suggested me to use findViewById on the inflated view by appending it with appropriate type and store the reference in a List, but I am able to set an OnClickListener only for the first view that is inflated.

I wanted to know if it is even possible to achieve what I am doing? In an other post I read that findViewById finds the first possible instance of the view it can find. Is that a problem in my case.

Please have a look at my code snippet

TextView[] tv=new TextView[l.size()]; 
for(int i=0;i<tv.length;i++){ 
tv[i]=(TextView)l.get(i).findViewById(R.id.mdsnew_type_sp); 
tv[i].setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View v) { 
showDialog(DATE_DIALOG_ID); } 
});
 //I have also tried this
 public void getData(){ 
 for(int i=0;i<l.size();i++){ 
 tv1=(TextView)l.get(i).findViewById(R.id.mdsnew_type_sp);
  }

But I am able to setOnClick Listener only for the first TextView and the rest are all ignored.

Here is another link that explains how I inflate my activity and a similar scenario but getting the information is not explained there Inflating a view multiple times in the same parent when a button is clicked

Any help will be rewarded, thanks in advance.

War es hilfreich?

Lösung

Since these TextViews have been added to a parent ViewGroup (in your case, a LinearLayout), you can traverse the parent's list of child views, and add an OnClickListener to each one:

for (int childPos = 0; childPos < myLayout.getChildCount(); childPos++) {
    myLayout.getChildAt(childPos).setOnClickListener(new OnClickListener() {
        @Override 
        public void onClick(View v) { 
            // ...
        }
    });
}

Andere Tipps

This may help

LanearLayout parentLayout = (LinearLayout)findViewById(R.id.main_ll);
 int count = parentLayout.getChildCount();
        for (int i = 0; i < count; i++)
     {
        View view = mainLl.getChildAt(i);
        if (view instanceof TextView) 
            {
              int id=view.getId();
            ((TextView) view).setText(" ");

            }
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top