首页 > 解决方案 > 如何在xamarin android中点击动态添加的textview?因为每当我点击 textview 它只显示最后一项文本,下面是我的代码

问题描述

      TableRow row;
       TextView txt;

 LinearLayout  tl = FindViewById<LinearLayout>(Resource.Id.tableLayout);
            var servicesData = DataServices.GetAllServices();
            try
            {
                foreach (var item in servicesData)
                {
                    row = new TableRow(this);
                    imgBtn = new ImageButton(this);

                    txt = new TextView(this) {Id=item.ServiceId };

                    btntxt = new Button(this);

                    txt.SetOnTouchListener(new View.IOnTouchListener)

                    String imgUrl = "https://careservicesapi.boffincoders.com/Images/" + item.ServiceIcon;


                    var imageBmp = GetImageBitmapFromUrl(imgUrl);

                   Drawable drawable = new BitmapDrawable(Resources, imageBmp);
                    Drawable drawable1 = new BitmapDrawable();
                    drawable.SetBounds(0, 0, 50, 40);

                    txt.SetMinimumHeight(100);
                    txt.SetMinimumWidth(100);
                    txt.SetHeight(100);
                    txt.TextSize = 10;
                    txt.Gravity = GravityFlags.Center;
                    txt.Text = item.ServiceName;
                    txt.Tag = item.ServiceId;
                    txt.Click += Txt_Click;

                  txt.SetCompoundDrawablesWithIntrinsicBounds(drawable1, drawable, drawable1, drawable1);
                   txt.Clickable = true;

                     tl.AddView(row);
                    row.AddView(txt);

                }

            }
 private void Txt_Click(object sender, EventArgs e)
        {
            var q = this.txt.Text;

        }

标签: androidxamarintextview

解决方案


它仅显示最后一项文本

因为您正在显示 的文本txt,所以它是最后一项。请从sender.

例如:

    private void Txt_Click(object sender, System.EventArgs e)
    {
        var q = ((TextView)sender).Text;
        Toast.MakeText(this, q, ToastLength.Short).Show();
    }

推荐阅读