Использование setOnCheckedChangeListener для динамически создаваемых переключателей - PullRequest
0 голосов
/ 01 ноября 2018

Я давно слежу за stackoverflow, но это мой первый пост здесь. Если есть ошибка, извините за это. Заранее спасибо.

Я создаю несколько радиокнопок и пытаюсь установить их идентификатор, начиная с 100. После второго выбора в радиогруппе он не снимает флажок с предыдущих радиокнопок и показывает, что все радиокнопки имеют идентичный идентификатор 110.

I/ContentValues: Radio button id Changed to:110 tea
I/ContentValues: Radio button id Changed to:110 tea
I/ContentValues: Radio button id Changed to:110 tea

Вот скриншот. https://image.ibb.co/mQHxtL/Screen-Shot-2018-11-01-at-12-58-25-AM.png

DashboardActivity.java

private List<Product> products_by_category;
private Menu menu;
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
        List<Product> arrayListProduct = Product.listAll(Product.class);
            radioGroup = (RadioGroup) findViewById(R.id.radioGroup_list);

        menu = new Menu(arrayListProduct);
        categories = menu.findAllCategories();

        addRadioButtons(menu.findAllCategories().size(), menu.findAllCategories());
        products_by_category = menu.findProductsByCategory(categories.get(0).getCatid());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i(TAG, "Radio button id Changed to:"+(i)+ " " + categories.get(i-101).getCategory());
                products_by_category = menu.findProductsByCategory(categories.get(i-101).getCatid());
                adapter.updateMenu(products_by_category);
            }
        });
}

public void addRadioButtons(int number,List<Category> categories) {
    for (int i = 1; i <= number; i++) {
       final RadioButton rdbtn = new RadioButton(getApplicationContext());
        rdbtn.setId(100+number);
        rdbtn.setTag(number);      rdbtn.setTextColor(ContextCompat.getColorStateList(this,R.color.custom_radio_color));             rdbtn.setTextColor(getResources().getColor(R.color.custom_radio_color,getTheme()));            
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        rdbtn.setBackground(getDrawable(R.drawable.custom_radio_btn));
        }else {
       rdbtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.custom_radio_btn,getTheme()));
        }
        rdbtn.setButtonDrawable(null);
        String str = categories.get(i-1).getCategory();
        rdbtn.setText(Const.makeCapitalFirstLettersOfAllWords(str));
        radioGroup.addView(rdbtn);
    }
    if(radioGroup.getChildCount() > 0)
        radioGroup.check(radioGroup.getChildAt(0).getId());
    }
}

activity_dashboard.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.berkayayaz.restaurantdemo.DashboardActivity">

<HorizontalScrollView
    android:id="@+id/radioGroup_scroll_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:fillViewport="true"
    android:scrollbars="none"
    app:layout_constraintEnd_toStartOf="@+id/ll_1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <RadioGroup
        android:id="@+id/radioGroup_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_border"
        android:gravity="center"
        android:orientation="horizontal">

    </RadioGroup>


</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>

Если я удалю «rdbtn.setId (100 + число);» line, setOnCheckedChangeListener работает нормально, но когда я нажал кнопку «Назад» и вернулся в «Активность панели мониторинга», переключатели были созданы с разными идентификаторами. Вот почему происходит сбой в меню menu.findProductsByCategory (Categories.get (i-101) .getCatid ()); adapter.updateMenu (products_by_category); "строка.

Я не мог найти причину, почему они продолжают оставаться проверенными Ценю за все подсказки. Хорошего дня.

Edit:

Я исправил свою проблему.

private List<Product> products_by_category;
private Menu menu;
private RadioGroup radioGroup;
private int firstRadiobuttonId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
        List<Product> arrayListProduct = Product.listAll(Product.class);
            radioGroup = (RadioGroup) findViewById(R.id.radioGroup_list);

        menu = new Menu(arrayListProduct);
        categories = menu.findAllCategories();

        addRadioButtons(menu.findAllCategories().size(), menu.findAllCategories());
        products_by_category = menu.findProductsByCategory(categories.get(0).getCatid());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i(TAG, "Radio button id Changed to:"+(i)+ " " + categories.get(i-firstRadiobuttonId).getCategory());
                products_by_category = menu.findProductsByCategory(categories.get(i-firstRadiobuttonId).getCatid());
                adapter.updateMenu(products_by_category);
            }
        });
}

public void addRadioButtons(int number,List<Category> categories) {
    for (int i = 1; i <= number; i++) {
       final RadioButton rdbtn = new RadioButton(getApplicationContext());
        rdbtn.setId(100+number);
        rdbtn.setTag(number);      rdbtn.setTextColor(ContextCompat.getColorStateList(this,R.color.custom_radio_color));             rdbtn.setTextColor(getResources().getColor(R.color.custom_radio_color,getTheme()));            
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        rdbtn.setBackground(getDrawable(R.drawable.custom_radio_btn));
        }else {
       rdbtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.custom_radio_btn,getTheme()));
        }
        rdbtn.setButtonDrawable(null);
        String str = categories.get(i-1).getCategory();
        rdbtn.setText(Const.makeCapitalFirstLettersOfAllWords(str));
        radioGroup.addView(rdbtn);
    }
    if(radioGroup.getChildCount() > 0)
        firstRadiobuttonId = radioGroup.getChildAt(0).getId();
        radioGroup.check(firstRadiobuttonId);
    }
}
...