putExtra 动态创建的视图 android

putExtra on dynamically created views android

我有一个字符串列表。我正在为它们中的每一个动态添加一个 RelativeLayout,并在每个 relativelayout 中动态添加 TextView。现在,当我单击时,我会将此 textview 值发送到下一个 activity。下面是代码。

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);
            }
        });

    }             

问题是,如果我有 10 个具有不同文本的 RelativeLayouts,并且我正在单击其中的任何一个,无论我单击哪个,都只会将 textview 的最后一个值传递给下一个 activity ;不是我点击的值。 请帮忙 谢谢

您总是得到最后一个,因为您在循环的每次迭代中都覆盖了成员 class。

您可以将 OnClickListener 设置为 TextView 而不是 RelativeLayout 并将 v 和点击的 View 转换为 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);
        }
});

尝试使用点击的视图,它是您的文本视图,将您的代码更改为 this.By 下面这样您将获得当前点击的文本视图的上下文,而不是最后一个。

rt.setOnClickListener(new OnClickListener() {

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

在onClick中,从相对布局中获取文本视图为

 TextView textView = (TextView) rl.getChildAt(0);
 String name= textView.getText().toString();