Кнопка просмотра списка не отправляет правильный номер другому действию

Кнопки 1–7 (по одной на каждую строку) правильно отправляют числа 1–7 на действие/экран компонента редактирования (числа соответствуют строке, в которой находится кнопка, в зависимости от «позиции»). Однако, когда я нажимаю кнопку 8-10, она по какой-то причине отправляет числа 1-3 на действие/экран редактирования компонента, и когда я снова нажимаю кнопки 1-3, все числа, отправленные на действие редактирования компонента, не синхронизированы. .

Я не понимаю, как кнопки для строк 1-7 отправляют правильные числа, но вдруг ряд 8 и выше не делают.

Пользовательский класс адаптера listview

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;

        //Row
        if (row == null)
        {
            row = LayoutInflater.From(mContext).Inflate(Resource.Layout.listview_row, null, false);
        }

        //Set component details
        TextView Category = row.FindViewById<TextView>(Resource.Id.txtViewCategory);
        Category.Text = allComponents[position].CategoryName;

        TextView Name = row.FindViewById<TextView>(Resource.Id.txtViewName);
        Name.Text = allComponents[position].Name;

        TextView Price = row.FindViewById<TextView>(Resource.Id.txtViewPrice);
        Price.Text = allComponents[position].Price;

        ImageButton editComponent = row.FindViewById<ImageButton>(Resource.Id.imgBtnEditComponent);

        //Take the user to the edit screen for a given component
        if (!editComponent.HasOnClickListeners)
        {
            editComponent.Click += (sender, e) =>
            {
                // Declare the activityas intent
                var intent = new Intent(mContext, typeof(Edit_componentActivity));

                //Store the row position
                var rowPostion = (position + 1);

                //Transfer the component's row to the edit screen
                intent.PutExtra("edit_component_row_position", rowPostion);

                //Start the activity of intent
                mContext.StartActivity(intent);
            };
        }

        return row;
    }

Активность редактирования компонента

        // Create your application here
        SetContentView(Resource.Layout.edit_component);

        //Get the component's row position
        var editComponentRowPosition = Intent.GetIntExtra("edit_component_row_position", 0);

        Toast.MakeText(this, editComponentRowPosition.ToString(), ToastLength.Long).Show();

        //Get the notes text view of the screen
        TextView editName = FindViewById<TextView>(Resource.Id.txtEditEditComponentName);

        //Assign the notes text view the component's notes
        editName.Text = editComponentRowPosition.ToString();

Вот несколько скриншотов.


person JAmes    schedule 13.01.2020    source источник
comment
Привет, не могли бы вы поделиться ссылкой на образец здесь, я проверю. Кстати, тестирую на местном сайте, не могу воспроизвести проблему.   -  person Junior Jiang    schedule 14.01.2020
comment
Что вы подразумеваете под образцом ссылки?   -  person JAmes    schedule 14.01.2020
comment
То есть примерный проект, только с выпуском. Если у вас есть время, вы можете поделиться им здесь.   -  person Junior Jiang    schedule 14.01.2020
comment
Привет, я воспроизвел вашу проблему, вы можете посмотреть ответ, когда у вас будет время.   -  person Junior Jiang    schedule 15.01.2020


Ответы (1)


Я воспроизвел вашу проблему на своем локальном сайте. Причина в том, что при использовании следующего кода для добавления щелчка для кнопки он не будет контролироваться. Когда вы нажимаете, метод GetView будет продолжать вызывать этот метод. Его не рекомендуется использовать в адаптере.

editComponent.Click += (sender, e) 

решение, в котором вместо него используется SetOnClickListener . Следующим образом :

ImageButton editComponent = row.FindViewById<ImageButton>(Resource.Id.imgBtnEditComponent);
ImageButton.Tag = position; //Set position as Tag for button
ImageButton.SetOnClickListener(this);

public void OnClick(View v)
{
    int position = (int)v.Tag;
    Console.WriteLine("-------------button click---------------" + (position + 1));
    // Declare the activityas intent
    var intent = new Intent(mContext, typeof(Edit_componentActivity));

    //Store the row position
    var rowPostion = (position + 1);

    //Transfer the component's row to the edit screen
    intent.PutExtra("edit_component_row_position", rowPostion);

    //Start the activity of intent
    mContext.StartActivity(intent);
}

Не забудьте наследовать View.IOnClickListener для класса адаптера.

person Junior Jiang    schedule 15.01.2020