Search code examples
androidandroid-layoutandroid-relativelayout

putExtra on dynamically created views android


I have a list of Strings. I am adding a RelativeLayout dynamically for each of them and adding TextViews dynamically in each of the relativelayouts. Now when I click, I am sending this textview value to the next activity. Below is the code.

for(int i = 0; i < Names.size(); i++)
    {                       
    textView = new TextView(this);
        textView.setText(Names.get(i)); 

         rt=new RelativeLayout(this);
        rt.setBackgroundResource(R.drawable.mednamedash);
        int curTextViewId = prevTextViewId + 1;
        int curRLId = prevRLId + 1;
        textView.setId(curTextViewId);
        rt.setId(curRLId);
        final RelativeLayout.LayoutParams params = 
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 
                                            RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.BELOW, prevTextViewId);


        final RelativeLayout.LayoutParams tvParams = 
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
                                                RelativeLayout.LayoutParams.WRAP_CONTENT);
        tvParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        rt.addView(textView, tvParams);


       prevTextViewId = curTextViewId;
        prevRLId=curRLId;
        noon.addView(rt, params);
        rt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i=new Intent(Dashboard.this,ReminderPopUp.class);
                i.putExtra("medicinename", textView.getText().toString());
                startActivity(i);
            }
        });

    }             

The problem is that if I have 10 RelativeLayouts with different texts and I am clicking on anyone of them, no matter which one I am clicking, only the last value of textview is passed to the next activity; not the value for which I clicked. Please help Thank you


Solution

  • You are getting always the last one because you are overriding the member class at every iteration of the loop.

    you could set the OnClickListener to the TextView instead of the RelativeLayout and cast v, the clicked View, to TextView

    textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i=new Intent(Dashboard.this,ReminderPopUp.class);
                i.putExtra("medicinename", ((TextView)v).getText().toString());
                startActivity(i);
            }
    });