Добавление кнопки к каждому элементу в массиве - PullRequest
0 голосов
/ 15 апреля 2019

Мой код записывает текущую долготу / широту и помещает в массив, и вы можете просмотреть всю историю этих записей в GPSHistory Activity.

        btnGPSHistory = FindViewById<Button>(Resource.Id.btnGPSHistory);
        btnGPSHistory.Click += (sender, e) =>
        {
            var intent = new Intent(this, typeof(GPSHistory));
            intent.PutStringArrayListExtra("Answer", liGPSAnswer);
            StartActivity(intent);
        };

Это преобразует значение типа double в строку, помещает строку и отправляет ее в массив.

    async private void GetGPS(object sender, EventArgs e)
    {
        if (here == null)
        {
            txtGPSAnswer.Text = "Try Again Later.";
            return;
        }

        dblLongitude = here.Longitude;
        dblLatitude = here.Latitude;

        strLongitude = dblLongitude.ToString("G");
        strLatitude = dblLatitude.ToString("G");

        strGPSAnswer = "Longitude: " + strLongitude + " Latitude: " + strLatitude;

        if (string.IsNullOrEmpty(strGPSAnswer))
        {
            txtGPSAnswer.Text = "";
        }
        else
        {
            txtGPSAnswer.Text = strGPSAnswer;
            liGPSAnswer.Add(strGPSAnswer);
            btnGPSHistory.Enabled = true;
        }                    
    }

Это из GPSHistory.cs

 namespace GPS2
 {
 [Activity(Label = "@string/GPSHistory")]
 public class GPSHistory : ListActivity
 {
     protected override void OnCreate(Bundle bundle)
     {
         base.OnCreate(bundle);

         // Create your application here
         var strLongitude = Intent.Extras.GetStringArrayList("Answer") ?? new string[0];

         this.ListAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, strLongitude);

    }
}
}

Код записывает штрафы долготы и широты и без проблем помещает их на страницу истории. Мой вопрос заключается в том, как прикрепить кнопку к каждому из этих элементов в массиве, который в основном говорит программе сделать эти координаты «текущими», чтобы программа могла просматривать эти координаты на карте. Спасибо.

1 Ответ

1 голос
/ 16 апреля 2019

Вы имеете в виду, что хотите добавить Button к элементу ListView? Если да, то вы должны использовать свой собственный адаптер следующим образом:

1.создать вам CustomAdapter :

class CustomAdapter : BaseAdapter, View.IOnClickListener
{

    private Dictionary<int, string> dictionary = new Dictionary<int, string>();

    List<string> items; //this is the data in my code ,you should replace your own data

    public CustomAdapter(List<string> value) // the parameter use your own data
    {

        //copy your data into the dictionary
        items = new List<string>();
        items = value;
        for (int i = 0; i < items.Count; i++)
        {
            dictionary.Add(i, items[i].ToString());
        }
    }

    public override Object GetItem(int position)
    {
        return items[position];
    }

    public override long GetItemId(int position)
    {
        return position;
    }


    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = items[position];
        View view = convertView;
        if (view == null) // no view to re-use, create new
            view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.item_listview, null);
        view.FindViewById<TextView>(Resource.Id.txt_location).Text = item;

        var button1 = view.FindViewById<Button>(Resource.Id.btn_set);
        button1.Tag = position;
        button1.SetOnClickListener(this);
        return convertView;
    }

    public override int Count { get; }
    public void OnClick(View v)
    {
        //do the thing you want,location is your strLongitude 
        var location = dictionary[(int) v.Tag];
    }
}

}

item_listview axml - ваш пользовательский макет:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="horizontal"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <TextView 
      android:id = "@+id/txt_location"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
   />

   <Button
      android:id = "@+id/btn_set"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Current Ones"
   />
</LinearLayout>

2.тогда в своей деятельности вы можете измениться так:

this.ListAdapter = new CustomAdapter(strLongitude);
...